3 ms·
The thing about the “Use XOR to swap two variables” trick is that it’s a version of this solution which works for any two real numbers (or integers): a = a -
by strenholme 6y ago
The thing about the “Use XOR to swap two variables” trick is that it’s a version of this solution which works for any two real numbers (or integers):
a = a - b
b = a + b
a = b - a
XOR is simply addition or subtraction modulo 2 for each bit, so making the above XOR looks like this:
a = a ^ b
b = a ^ b
a = b ^ a
- volta87 6y agoThe article touches on this, since its an important realization. In C, however, if the integers are not unsigned, the add/sub version exhibits UB on overflow, because C unnecessarily ties signed/unsignedness with overflow behavior (UB, two's complement, etc.). Not that this is important, but could hint why this trick is more often shown with XOR than with add/sub.