What’s the precedence of comma operator inside conditional operator in C++?

The first one is equivalent to:

(true  ? (++x, ++y) : (--x)), --y; 

The second one is equivalent to:

(false ? (++x, ++y) : (--x)), --y; 

Thus the --y is always executed. In the first line, the increments are executed first so x = 1, y = 0 is expected. In the second line, the decrement of x is executed first so x = -1, y = -1 is expected.


As noted in a comment (to another answer) by Barmar:

And in case anyone is wondering why the comma between ++x and ++y doesn’t have the same effect, it’s because (true? ++x) would not be valid at all. So the compiler keeps scanning until it finds the :, but beyond that it stops when it reaches a lower precedence operator [(, in this example) or the end of statement].

Leave a Comment