Question

Given that x is initialised to 0 before each statement on the left executes, the result is the value displayed on the right:

(++x + ++x) + ++x == 7
++x + (++x + ++x) == 9
++x + ++x + ++x   == 7

Why does the first statement result in 7 and the second statement result in 9 ???

Why is the result of the first statement the same as the third statement ???

Was it helpful?

Solution

Well it is undefined behaviour... it is likely that the compiler will write code that looks like this.

(++x + ++x) + ++x == 7
x = 0
x++ => 1 (x)
x++ => 2 (x)
r = 2 + 2
x++ => 3 (x)
r + x = 7

And this

++x + (++x + ++x) == 9

x++ => 1  x + (++x + ++x)
x++ => 2  x + (x + ++x)
x++ => 3  x + (x + x)
//You'll have x + (x + x) where x is 3
// Now
r = 3 + 3
x + r = 9

Annnd all this is valid for the compiler you're currently using. Other compilers could be smart enough to return the same results some don't. It might even depend on the level of optimization and it all stand down to undefined behaviour.

In conclusion, don't write code that looks like this. I'm pretty sure that your compiler is outputting some warnings about this.

To explain a bit more what it's happening is that you're modifying a register in place. Before it can do operations, it has to evaluate the "++". So one might think that you end up with:

1 + 2 + 3 => 5

But in reality, since the ++ isn't supposed to allocate new memory, it will increase the value in place. The order from left to right might be forced using parenthesis. So in one case, it will increase 2 times then a third time when it sums r + x and the version with parenthesis forces every ++ from left to right and then sum x + r. But since it's undefined behaviour. It doesn't really mean anything. Just don't do that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top