Reputation:
I understand there is no sequence point here before the semicolon, but is there a plausible explanation for the dereferenced pointer to use the old value 2 in the expression?
Or can it be simply put down as undefined behaviour?
int i=2;
int *x=&i;
*x+=*x+=i+=7;
Result:
i= 13
Upvotes: 0
Views: 129
Reputation: 196
The behaviour isn't undefined, it is down to the way the compiler breaks down the expression and pushes the intermediate results onto the stack. The two *x
s are calculated first (both equal 2) and are pushed onto the stack. Then i
has 7 added to it and equals 9. Then the second *x
, which still equals 2, is pulled off the stack, and added, to make 11. Then the first *x
is pulled off the stack and added to the 11 to make 13.
Look up Reverse Polish Notation for hints on what is going on here.
Upvotes: -3
Reputation: 355187
It is "simply" undefined behavior.
That said, the compiler probably emits code that reads the value of i
once then performs all the arithmetic, then stores the new value of i
.
The obvious way to find out the real explanation would be to go look at the assembly generated by the compiler.
Upvotes: 7