The grammar of the conditional ooperator is
logical-or-expression ? expression : assignment-expression |
As you see after
':' assignment-expression is followed.
Assignment-expression has a higher priority compared with the comma operator. So if you have for example the following expression
false ? expression1 : ++x, ++y;
then it is equivalent to the following record
( false ? expression1 : ++x ), ++y;
As you see the expression ++y will be executed in any case irrespective of whether the first value before the question mark is false or true.
Let consider your original code snip
1 2 3 4 5 6 7 8
|
{
int value = 1;
int x = 1;
int y = 1;
value ? ++x, ++y : --x, --y;
std::cout << x << " " << y;
}
|
It can be rewritten as
1 2 3 4 5 6 7 8
|
{
int value = 1;
int x = 1;
int y = 1;
( value ? ++x, ++y : --x ), --y;
std::cout << x << " " << y;
}
|
As value is equal to 1 then ++x and ++y are executed. x becomes equal to 2 and y also becomes equal to 2. But after the conditional operator there is --y (the comma ooperator). So y becomes equal to 1. And the output confirms this
Now change the initial value of 'value' to 0. Then we will get
1 2 3 4 5 6 7 8
|
{
int value = 0;
int x = 1;
int y = 1;
( value ? ++x, ++y : --x ), --y;
std::cout << x << " " << y;
}
|
In this case at first --x will be executed and x will be equal to 0 and after that --y will be executed and y will be equal to 0.
So --y will be executed in any case because it is executed
after the conditional operator due to operators' priority.
You could rewrite your code snip the following way
1 2 3 4 5 6 7 8
|
{
int value = 1;
int x = 1;
int y = 1;
value ? ++x, ++y : ( --x , --y );
std::cout << x << " " << y;
}
|
In this case --y (together with x) would be executed only in the case when 'value is equal to 0.