Math Fundamentals18 sections · 814 units
Open in Course

Swapping Without a Temporary

XOR swap trick

XOR lets you swap two variables without using a temporary variable. Here's how:

a:=aba := a \wedge b

b:=abb := a \wedge b

a:=aba := a \wedge b

After these three operations, aa and bb have swapped values. Why? After the first line, aa holds aba \wedge b. In the second line, b:=(ab)b=ab := (a \wedge b) \wedge b = a (using xx=0x \wedge x = 0 and x0=xx \wedge 0 = x). In the third line, a:=(ab)a=ba := (a \wedge b) \wedge a = b. It's a clever trick, though using a temporary is usually clearer and just as fast.