XOR swap (Stephan Brumme, bits)
stephan-brumme‘s page on swapping two values without a temporary, from his benchmarked bits.stephan-brumme.com collection (each trick shipped with assembler output, timings, and source).
The trick
Three XORs exchange two integers using the identity a ^ b ^ a = b:
a ^= b;
b ^= a;
a ^= b;
The caveats (the reason it’s a cautionary tale, not advice)
- Aliasing hazard: must not be applied to the same storage twice —
swapXor(x, x)zeroes the value (each^=against itself yields 0). The temp-variable swap has no such trap. - Not faster on modern CPUs: Brumme benchmarks it as slower than the obvious temp-variable swap across Intel processors — registers and store-to-load forwarding make the temp version cheaper, and the three XORs carry a serial dependency chain. The trick’s old appeal (saving a register) no longer pays.
Why it’s here
The cleanest single illustration of this spoke’s central lesson (branchless-programming): a famous bit trick that is elegant, correct-with-caveats, and obsolete as an optimization. Belongs with the other Brumme/bit-twiddling-hacks entries as a technique to understand rather than deploy.
Tier
T2 — an author-maintained technical reference with disassembly + benchmarks (neutral, no vendor interest), though single-author and self-published. Benchmark figures are dated/CPU-specific snapshots.
Related
branchless-programming · bit-manipulation · stephan-brumme · branchless-abs · bit-twiddling-hacks