"warning: operation of ... may be undefined"用于三元操作 - 不是if/else块

"warning: operation of ... may be undefined" for ternary operation -- not if/else block

本文关键字:操作 三元 不是 else if operation warning of may 用于 undefined      更新时间:2023-10-16

这是我的代码:

int main() {
    static int test = 0;
    const int anotherInt = 1;
    test = anotherInt > test ? test++ : 0;
    if (anotherInt > test)
        test++;
    else
        test = 0;
    return 0;
}

这是我构建它时生成的警告:

../main.cpp:15:40: warning: operation on ‘test’ may be undefined [-Wsequence-point]
  test=     anotherInt>test ? test++ : 0;
                                        ^

为什么C++对三元运算发出警告,而不是常规if..else语句?

它们不等效。请注意,在三元运算符表达式中,您将结果分配给test

if条件更改为:

if(anotherInt > test)
    test = test++;  // undefined!

您可能也会在这里看到相同的警告。

你可能知道在这段代码中:otherInt>test ? test++ : 0; 计算机可能先运行 test++,也许运行 otherInt>test ? first.so 表达式中,如果使用变量,u 不应该在这个表达式中的其他地方更改它。您可以将 test++ 更改为 test+1。