1. One-Liner
Use a ^= b; b ^= a; a ^= b to exchange values without a temporary—pure XOR algebra.
2. The Problem It Solves
Micro-optimization curiosity, embedded registers, understanding XOR properties—not always faster than modern compiler swap.
3. The Core Idea
Since x^x=0 and x^0=x, chaining XORs toggles bits to carry values across variables—fails if a and b alias same location.
4. How It Works (Step-by-Step)
| Step | Action |
|---|---|
| 1 | Check a and b not same address |
| 2 | a ^= b |
| 3 | b ^= a (now holds old a) |
| 4 | a ^= b (now holds old b) |
5. Dry Run Example
5 and 7 swap via XOR toggles—trace bits mentally in interview if asked.
6. Key Properties
| Property | Detail |
|---|---|
| Aliasing | Undefined/wrong if &a==&b |
| Integers | Not for floats directly |
| Compiler | Often uses temp anyway |
7. Where It Is Used
| Domain / System | Use |
|---|---|
| Embedded | Register tricks |
| Obfuscation | XOR patterns |
| Teaching | XOR properties |
8. Interview Tips
Modern code: prefer std::swap—optimizers know best. Mention add/sub swap overflow risks too.
9. Comparison with Other Algorithms
| Technique | Notes |
|---|---|
| Temp swap | Clearer, safe |
| Arithmetic swap | Overflow hazard |
| Tuple swap | Pythonic |
10. Complexity
| -- | -- |
|---|---|
| Time | O(1) |
| Space | O(1) |
Implementation Example (PYTHON)
def xor_swap(a, b):
if a is b:
return a, b
a ^= b
b ^= a
a ^= b
return a, b