Yue Wang
Yue Wang

Reputation: 1750

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

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?

Upvotes: 5

Views: 534

Answers (2)

wilx
wilx

Reputation: 18228

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.

Upvotes: 4

Michael Burr
Michael Burr

Reputation: 340218

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.

Upvotes: 10

Related Questions