#516 – The Assignment Operator is Right-Associative

An expression can contain more than one assignment operator.  If this is the case, the assignments are evaluated from right to left.  Consider the code fragment below.

int x = 12;
int z = 24;
int i = x = z;

Because the assignments are done from right to left, the variable x is first assigned the value that is stored in z (24).  At this point, both x and z have the value of 24.

Next, i is assigned the value that is the result of the first assignment (24).  At this point, x, z and i now all have the value of 24.

Because this behavior can be a little confusing,  it’s generally preferable to do each assignment on a separate line.

int x = 12;
int z = 24;
x = z;
int i = x;