The following expression :-
int main()
{
int x=2, y=9;
cout << ( 1 ? ++x, ++y : --x, --y);
}
gives the following output:-
9
As per my understanding, it should return ++y which should be 10. What went wrong?
The following expression :-
int main()
{
int x=2, y=9;
cout << ( 1 ? ++x, ++y : --x, --y);
}
gives the following output:-
9
As per my understanding, it should return ++y which should be 10. What went wrong?
The ternary operator (? and :) has higher precedence compared to the comma operator (,). So, the expression inside the ternary conditional is evaluated first and then the statements are split up using the comma operator.
1 ? ++x, ++y : --x, --y
essentially becomes
(1 ? (++x, ++y) : (--x)), (--y)
/* ^^^^^^^^^^^^^^^^^^^^^^^^ is evaluated first by the compiler due to higher position in
the C++ operator precedence table */
You can eliminate the problem by simply wrapping the expression in parentheses:
1 ? (++x, ++y) : (--x, --y)
This forces the compiler to evaluate the expression inside the parentheses first without any care for operator precedence.