I tried some code to swap two integers in Java without using a 3rd variable, using XOR.
Here are the two swap functions I tried:
package lang.numeric
Because a ^= b ^= a ^= b; is parsed like:
a ^= b ^= a ^= b;
a ^= (b ^= (a ^= b));
Which can be reduced to:
a ^= (b ^= (a ^ b));
So b will have the value b ^ (a ^ b) and finally a will be a ^ (b ^ (a ^ b).
b
b ^ (a ^ b)
a
a ^ (b ^ (a ^ b)