【问题标题】:"warning: operation of ... may be undefined" for ternary operation -- not if/else block [duplicate]三元运算的“警告:...的运算可能未定义”——不是 if/else 块 [重复]
【发布时间】:2016-02-14 06:51:19
【问题描述】:

这是我的代码:

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 语句?

【问题讨论】:

  • 您的 if 不等价。你的三元正在做test = test++;
  • 您将test++ 更改为test=test++,这有很大的不同。
  • 请注意,undefined 指的是表达式的输出,而不是任何变量的输出。不同的编译器会以不同的方式评估“text = text++”;因此,它会被标记。

标签: c++ ternary-operator


【解决方案1】:

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

将if 条件更改为:

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

您可能也会在此处看到相同的警告。

【讨论】:

  • 是的,我收到了同样的警告。如果我想使用三元运算符,我该怎么办?
  • @Username 将test++ 替换为test + 1。
  • test = anotherInt > test ? test+1 : 0;
【解决方案2】:

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

【讨论】:

  • 不,这不是问题所在。三元运算符的条件保证在任一表达式之前被计算。
猜你喜欢
  • 2015-06-05
  • 2021-03-31
  • 1970-01-01
  • 2012-07-23
  • 2013-06-24
  • 2018-08-07
  • 2010-12-12
  • 2021-01-03
  • 1970-01-01
相关资源
最近更新 更多