It's an exercise from C++ Primer 5th:
Exercise 4.33: Explain what the following expression does(Page158): someValue ? ++x, ++y : --x, --y
The codes:
bool someVlaue = 1;
int x = 0;
int y = 0;
someVlaue ? ++x, ++y : --x,--y;
std::cout << x << std::endl << y << std::endl;
I tried Gcc4.81
and Clang3.5
, both gave me:
1
0
Press <RETURN> to close this window...
Why not 1
and 1
? Can anyone explain how it was interpreted?
Precedence is the priority for grouping different types of operators with their operands. Associativity is the left-to-right or right-to-left order for grouping operands to operators that have the same precedence.
Operators Associativity is used when two operators of same precedence appear in an expression. Associativity can be either Left to Right or Right to Left. For example: '*' and '/' have same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.
The precedence of operators in C dictates the order in which the operators will be evolved in an expression. Associativity, on the other hand, defines the order in which the operators of the same precedence will be evaluated in an expression.
Programmers can alter the precedence and associativity rules by placing parentheses in expressions.
Because of the very low precedence of the comma operator, the expression
someValue ? ++x, ++y : --x,--y;
is equivalent to:
(someValue ? ++x, ++y : --x),--y;
So the ++x, ++y
expression is executed (setting x
and y
to 1), followed by the expression --y
at the end, restoring y
to 0.
Note - the comma operator introduces a sequence point, so there is no undefined behavior from modifying y
more than once.
The expression
someValue ? ++x, ++y : --x, --y
is evaluated as
(someValue ? ((++x), (++y)) : (--x)), (--y)
As you can see, the y
is modified twice, once incremented and once decremented, thus the result is 1 0
and not 1 1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With