C++ vs assembly code

x=10; l= ++x + x++ + x
At first I thought evaluation takes place from right to left. So we have x=10
then, x++= 10 (later it will be converted to 11 for next evaluation)
then, ++x= 12 ( 11 +1) hence, we get, 12+10+10=32!
But I executed the program in three different compilers(g++ , turboC++ and DevC++) and I found that the answer is 33. I couldn't understand the its behind-the-scene working so I decided to deassemble the executable file and check its machine code to see if I could get anything out of it. Here's the machine code
1
2
3
4
5
6
7
mov [esp+0C],0000000A; this is variable x mov
 [esp+08],00000000; this is l cuz I initialised l to 0
 inc [esp+0C]
 mov eax,[esp+0C]
 add eax,eax
 add eax,[esp+0C] ;here we get accumulator register with value 33
 mov [esp+08],eax ;moving 33 to variable l

I cannot connect the C++ code with machine code. Can anyone help?
Last edited on
Addition and prefix evaluate left-to-right, not right-to-left. Assignment evaluates right-to-left.
The code has undefined behaviour, so no matter what the compiler does, it is equally wrong.

1
2
3
4
5
6
7
8
y = ++x + x++ + x;
// is similar to
y = A + B + C;

// The A and B have to be evaluated before the first addition can be evaluated
// The order of evaluating A and B is up to implementation
// The C has to be evaluated before the second addtion, but can be evaluated before the first addition
// Therefore, the C can be before A and B, between them, or after them 
@ispil: In that case it should evaluate to 11+11+12. That makes it 34 but it's evaluating to 33.
@keskiverto: Do you mean that the answer to such questions is unpredictable?
Yes.

See the sequence point rules: http://en.cppreference.com/w/cpp/language/eval_order
Heh, I was trying to figure out whether it was undefined or not, but for some reason I blanked on that. Yes, the code here will change depending on where you compile it more than what you compile it with.
It has to be undefined, it changes x's value multiple times during the assignment.
Topic archived. No new replies allowed.