Proofs: XOR swap
These are the human proofs of XOR swap, at full length.
The XOR swap exchanges two distinct cells and leaves one cell unchanged full
This proof shows: correctness.
Fix a word size and let . For , is the word whose bit is , for .
Lemma (laws of XOR). For all : (1) ; (2) ; (3) ; (4) .
Proof. Each law is an equation between two words, so it is enough to check it at each bit position . At position the operation is addition modulo 2 on . Addition modulo 2 is associative and commutative, , and .
The laws hold for any reading of the words, signed or unsigned, because they are about bit patterns.
Theorem. Let be a memory of -bit cells. Let and before the call XOR-SWAP. After the call, and when , when , and no other cell changes.
Proof. Lines L2 to L4 write only to and , and line L1 writes nothing, so no other cell changes.
Case . Line L1 returns before any write, so .
Case . Then and are different cells, and a write to one does not change the other. We follow the two cells.
- Line L2 sets . The cell still holds .
- Line L3 sets . By (1), this is ; by (4), it is ; by (3), it is . The cell still holds .
- Line L4 sets . By (2) and (1), this is ; by (4) and (3), it is . The cell still holds .
So and .
Why line L1 is needed. Remove line L1 and let , with . Line L2 sets by (4). Line L3 then sets , and line L4 does the same. So the cell ends with 0, and the result is wrong for each . For the result happens to be right.
Termination and cost. There is no loop. The procedure runs at most one comparison and three XOR assignments, so it stops after a constant number of steps.