conditional operator

Why does this print 11 12:

1
2
3
4
    int x = 11, y = 11;

    (x > 10 && y > 10) ? ++x, ++y : --x, --y;
    cout << x << " " << y; // 11 12 


If I parenthesize (++x, ++y), it is still 12 11, but if I parenthesize (--x, --y) but not the ++ ones it is 12 12!

The condition is true so why does the -- affect my ++ ones?
It is due to the definition of the conditional operator and its priority.

The conditional operator is defined as

conditional-expression:
logical-or-expression
logical-or-expression ? expression : assignment-expression

The assignment operator has higher priority compared with the comma operator

So your expression is equivalent to

(( x > 10 && y > 10 ) ? ++x, ++y : --x ), --y;
Last edited on
@Codeez

Why does this print 11 12:
int x = 11, y = 11;

(x > 10 && y > 10) ? ++x, ++y : --x, --y;
cout << x << " " << y; // 11 12


By the way your original post contains a typo. There should be 12 11 instead of 11 12 as you wrote.:)



@vlad thanks again. I find that a bit bizzare though considering I parenthesized the condition before the ?.
In my example there was a typo. The condition should be enclosed in parentheses.:)
Hah, likewise! Thanks for the explanation :)
Topic archived. No new replies allowed.