“警告:...的操作可能未定义”用于三元运算——不是 if/else 块

Use*_*ame 6 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

为什么 C++ 给我一个关于三元运算的警告,而不是正则if..else语句?

Yu *_*Hao 4

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

if条件改为:

if(anotherInt > test)
    test = test++;  // undefined!
Run Code Online (Sandbox Code Playgroud)

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

  • @用户名将“test++”替换为“test + 1”。 (3认同)