A little caution note on chaining compound assignment.

First of, what is a compound assignment.? A compound assignment is when you use an operator in conjunction with the assignment operator
a += b; // The same as a = a + b
Now consider that you want to write a swap routine using XOR
a=a^b;
b=a^b;
a=a^b;
this could be transformed to compound operators
a^=b;
b^=a;
a^=b;
If you haven't read the spec on how assignments works, you would think that chaining these operators would be the same
a^=b^=a^=b;
But you will be surprised to learn that the latter two pieces of code behave differently.

Chapter 7.16.2 in the C# specification explains what is going on. When using the compound operator the left side operand is evaluated only once. this means in practice that when you chain the operators like in the last example, then all the left side operands are evaluated before any execution, thus  the chain doesn't get the intermediate a and b updated as when you make it line by line.

Comments