I am trying to swap 2 variables with an XOR operation.
int a = 5;
int b = 4;
a ^= b ^= a ^= b;
This code works in Objective-C and C++, but doesn't work in C# and JavaScript, and I can't understand the reason.
I am trying to swap 2 variables with an XOR operation.
int a = 5;
int b = 4;
a ^= b ^= a ^= b;
This code works in Objective-C and C++, but doesn't work in C# and JavaScript, and I can't understand the reason.
This has to do with a slight difference in how C/C++ handle the op-assignment ( +=, ^= and others) operator compared to C# / Javascript.
In Javascript the variable(s) being assigned to do not change value until after the statement is completed. To simplify the math, suppose we have this code in Javascript:
var a = 5;
var b = 4;
a += b += a += b;
In javascript this sets a = 18 (a = 5 + 4 + 5 + 4) and b = 13 (b = 5 + 4 + 4). This is because of the fact that no variables change values until the whole statement has completed.
In contrast, in C/C++ variable assignment takes places when each subexpression of += takes place. Consider corresponding C code:
int a = 5;
int b = 4;
a += b += a += b;
This gives a = 22, which is obtained as follows: First the last part of the expression, a += b, is evaluated. This results in the value of 9. then b+= 9 is evaluated, giving b = 13. Then a+= 13 is evaluated giving a = 22. The value of b stands at 13.