Quiz Entry - updated: 2026.07.07
What is the XOR swap trick and why does it work?
Three XORs swap two variables with no temporary — but it silently zeroes the value if both operands are the same memory location.
// a = a XOR b
a ^= b;
// b = b XOR (a XOR b) = a
b ^= a;
// a = (a XOR b) XOR a = b
a ^= b;
Why it works: XOR is self-inverse: x ^ x = 0 and x ^ 0 = x
Trace through:
Start: a=5 (101), b=3 (011)
a ^= b: a = 110 (6)
b ^= a: b = 011 ^ 110 = 101 (5) ← original a!
a ^= b: a = 110 ^ 101 = 011 (3) ← original b!
Warning: Fails if a and b are the same memory location (a ^= a = 0).
Go deeper:
XOR swap algorithm (Wikipedia) — the proof it works and why the aliasing case breaks it.