c++ - "warning: operation of ... may be undefined"用于三元运算——不是 if/else block

标签 c++ ternary-operator

<分区>

这是我的代码:

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!

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

关于c++ - "warning: operation of ... may be undefined"用于三元运算——不是 if/else block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35389177/

相关文章:

C++ 检索自 1970 年 1 月 1 日以来的毫秒数 : cannot open source file sys/time. h

c++ - QSerialPort 新信号槽语法没有匹配的成员函数调用 'connect'

javascript - 将 JavaScript 三元运算符转换为 if than else 语句

javascript - 在 View 中使用三元运算符

c++ - VC++ 2008 中 stdio.h 的编译错误

c++ - 运算符 '==' 没有左操作数

c# - 使用 C# 代码读取写入文件的 C++ 结构

ruby - 你如何理解 Ruby 中的这个三元条件?

javascript - 大规模创建一个简单的 react 多三元运算符来合并数组?

javascript - 这个 JavaScript 是如何工作的?