6

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?

5gon12eder
  • 24,280
  • 5
  • 45
  • 92
Username
  • 3,463
  • 11
  • 68
  • 111

2 Answers2

4

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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
-3

u may know that in this code: anotherInt>test ? test++ : 0; the computer maybe run test++ first,maybe run anotherInt>test ? first.so in a expression,if u use a variable ,u should not change it in some other place in this expression .U can change test++ to test+1.

  • 3
    No, that's not the problem. The condition of the ternary operator is guaranteed to be evaluated before either expression. – 5gon12eder Feb 14 '16 at 07:04