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:=a∧ba := a \wedge b

b:=a∧bb := a \wedge b

a:=a∧ba := a \wedge b

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