XOR swap

Swap two integers in place using three XORs, with no temporary variable.

Time O(1)Space O(1)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

After a ^= b, a holds the XOR of both original values while b is untouched, so b ^= a then XORs b with that combined value, which cancels b's own bits and leaves the original a. Now a holds (original a) ^ (original b) and b holds (original a), so a ^= b cancels the original a bits and leaves the original b. Three XORs, no spare storage.

Code

public static void XorSwap(ref int a, ref int b) {
    a ^= b;
    b ^= a;
    a ^= b;
}
static void xorSwap(int[] v, int i, int j) {   // Java has no ref: swap two slots of an array (i != j)
    v[i] ^= v[j];
    v[j] ^= v[i];
    v[i] ^= v[j];
}
void xorSwap(int& a, int& b) {
    a ^= b;
    b ^= a;
    a ^= b;
}
def xor_swap(a: int, b: int) -> tuple[int, int]:  # Python has no ref parameters, so return the pair
    a ^= b
    b ^= a
    a ^= b
    return a, b

Tips

In the .NET library

It is a neat trick but rarely used in real code: a normal temp-variable swap is clearer and, on most hardware, just as fast or faster.