← Back to Games

🔄 XOR Swap Lab

Swap two numbers using XOR - no temporary variable needed!

⚡ The Swap Chamber
A
5
B
9
1.
a = a ^ b
2.
b = a ^ b
3.
a = a ^ b

📚 XOR Swap Algorithm

The XOR swap trick uses the properties of XOR to swap without a temp variable:

// XOR Properties:
// a ^ a = 0 (same values cancel)
// a ^ 0 = a (XOR with 0 = identity)
// a ^ b = b ^ a (commutative)

// The Algorithm:
a = a ^ b // a now holds a⊕b
b = a ^ b // b = (a⊕b)⊕b = a
a = a ^ b // a = (a⊕b)⊕a = b

Note: This only works when a and b are different variables. If a and b point to the same memory, both become 0!