Search code examples
coperators

What are all the details behind the operation of += and similar operators in C?


Yes, I know, this seems like a no-brainer to google. I know full well that x += y does the same thing as x = x + y. That's not my question here.

My question is what on earth this line of code is doing (taken from the SplitMix64 PRNG code):

uint64_t z = (x += 0x9e3779b97f4a7c15);

Notice the += in the middle of the line. (To be clear, x is also a uint64_t.)

What I think this will do is:

  • Add 0x9e3779b97f4a7c15 to x and produce a result.
  • Assign that result to x.
  • Furthermore assign that same result to z.

A quick test makes me think I'm probably right:

#include <stdio.h>

int main() {
  int x;
  int y;
  x = 5;
  y = (x += 6); 
  printf("%d\n", x); 
  printf("%d\n", y); 
}

This prints "11" twice on my system (compiled with a simple gcc test.c).

Just to be sure, I'd like to confirm that this is how things work (and also find out if there's any other fancy corner cases you can end up with when using += and its siblings). I can't find info about this in my search attempts (everything about it seems to assume that you're using += in the simple x += y scenario).


Solution

  • What you're seeing here is not specific to compound assignment operators like += but to assignment operators in general. For any assignment operator, the entire expression has a value, namely the value that was assigned.

    This is spelled out in section 6.5.16p3 of the C standard:

    An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment, but is not an lvalue.

    So your assessment is correct.