Swapping w/o Temporaries

06/01/2024
Go back

Perhaps only useful within compilers, and otherwise a party trick.

A mathematician, a computer scientist, and a first year undergraduate walk into a bar. The first two tell the latter to get out, but instead we'll pretend we're in Britain.

The bartender asks them to write a function that swaps two integers. Here's what each writes:

First year undergraduate:

void swap(int& a, int& b) { int c = a; a = b; b = c; }

Mathematician:

void swap(int& a, int& b) { a = a + b; b = b - a; a = a - b; }

Computer Scientist:

void swap(int& a, int& b) { a = a ^ b; b = a ^ b; a = a ^ b; }

The computer scientist proceeds to implement argument register swapping with no temporaries in their compiler using the theorem that any permutation is a series of swaps.