Search code examples
cpointerschainingundefined-behavior

+= Operator Chaining (with a dash of UB)


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

Solution

  • 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.