Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Here's my code:

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

Here's the warning produced when I build it:

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

Why does C++ give me a warning on the ternary operation, but not the regular if..else statement?

like image 721
Username Avatar asked Feb 14 '16 06:02

Username


1 Answers

They are not equivalent. Note that in the ternary operator expression, you assigned the result to test

Change the if condition to:

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

You would probably see the same warning here as well.

like image 169
Yu Hao Avatar answered Nov 14 '22 23:11

Yu Hao