"warning: operation of ... may be undefined" 用于三元运算——不是 if/else 块
"warning: operation of ... may be undefined" for ternary operation -- not if/else block
这是我的代码:
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!
您可能也会在此处看到相同的警告。
你可能知道在这段代码中:anotherInt>test?测试++:0;计算机可能先 运行 test++,也许 运行 anotherInt>test ? first.so 在一个表达式中,如果你使用一个变量,你不应该在这个表达式的其他地方改变它。你可以将 test++ 更改为 test+1。
这是我的代码:
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!
您可能也会在此处看到相同的警告。
你可能知道在这段代码中:anotherInt>test?测试++:0;计算机可能先 运行 test++,也许 运行 anotherInt>test ? first.so 在一个表达式中,如果你使用一个变量,你不应该在这个表达式的其他地方改变它。你可以将 test++ 更改为 test+1。