Search code examples
c++operator-precedencecomma-operator

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


What's happening here?

#include <iostream>
using namespace std;

int main(){

    int x=0,y=0;
    true? ++x, ++y : --x, --y; 
    cout << "x: " << x << endl;
    cout << "y: " << y << endl; //why does y=0 here?

    x=0,y=0;
    false ? ++x, ++y : --x, --y; 
    cout << "x: " << x << endl;
    cout << "y: " << y << endl;
}

x: 1
y: 0

x: -1
y: -1

The second case seems fine. I would expect both x and y to increment to 1 in the first case but only the left hand operand increments.


Solution

  • 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].