Search code examples
c++ternary-operatoroperator-precedence

How is this ternary conditional expression executed?


int x = 5,y = 10;
bool boolean = 0;
int k = (boolean ? ++x, ++y : --x, --y);
cout<<k;

When boolean is 0,it outputs 9, however when it is 1 it outputs 10.I know this is happening because of precedence but cannot exactly figure out how is it happening, please help me understand this.

NOTE:I know I can get the expected output if I use parenthesis,or better write a clean code,I am just using this to understand how compiler would evaluate expressions like these according to precedence.


Solution

  • , has lower precedence than ?:. Which means that the full parenthesising is:

    int k = ((boolean ? (++x, ++y) : --x), --y);
    

    As you can see, k is always initialised to the value of --y. It's just that if boolean is true, ++y happens before that.


    When looking for the full parenthesis form of an expression, think of it as constructing the expression tree (where the lowest-precedence operator is at the root).

    Find the lowest-precedence operator in an expression, and parenthesise its left-hand side argument and its right-hand side argument. Repeat recursively within the sub-expressions just parenthesised.