Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the compiler interpret this expression, in terms of Precedence and Associativity?

Tags:

c++

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?

like image 826
Yue Wang Avatar asked Apr 03 '14 05:04

Yue Wang


People also ask

What is precedence and associativity in an expression?

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.

What do you understand by precedence and associativity of an operator explain with example?

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”.

How does precedence and associativity play a role in evaluating an expression?

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.

What can you use to alter the precedence and associativity rules in expressions?

Programmers can alter the precedence and associativity rules by placing parentheses in expressions.


2 Answers

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.

like image 64
Michael Burr Avatar answered Nov 03 '22 00:11

Michael Burr


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.

like image 23
wilx Avatar answered Nov 03 '22 00:11

wilx