开发者

+= Operator Chaining (with a dash of UB)

开发者 https://www.devze.com 2023-02-06 17:03 出处:网络
开发者_JAVA技巧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?

开发者_JAVA技巧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


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.


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 *xs 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消