Conventional swapping requires the use of a temporary storage variable. Using the XOR swap algorithm, however, no temporary storage is needed. The algorithm is as follows: X := Y XOR X; // XOR the values and store the result in X Y := X XOR Y; // XOR the values and store the result in Y X := Y XOR X; // XOR the values and store the result in X Since XOR is a
commutative operation, either X XOR Y or Y XOR X can be used interchangeably in any of the foregoing three lines. Note that on some architectures the first operand of the XOR instruction specifies the target location at which the result of the operation is stored, preventing this interchangeability. The algorithm typically corresponds to three
machine-code instructions, represented by corresponding
pseudocode and assembly instructions in the three rows of the following table: In the above System/370 assembly code sample, R1 and R2 are distinct
registers, and each operation leaves its result in the register named in the first argument. Using x86 assembly, values X and Y are in registers eax and ebx (respectively), and places the result of the operation in the first register (Note: x86 supports XCHG instruction so using triple XOR do not make sense on this architecture). In RISC-V assembly, value X and Y are in registers x10 and x11, and places the result of the operation in the first operand. However, in the pseudocode or high-level language version or implementation, the algorithm fails if
x and
y use the same storage location, since the value stored in that location will be zeroed out by the first XOR instruction, and then remain zero; it will not be "swapped with itself". This is
not the same as if
x and
y have the same values. The trouble only comes when
x and
y use the same storage location, in which case their values must already be equal. That is, if
x and
y use the same storage location, then the line: X := X XOR Y sets
x to zero (because
x =
y so X XOR Y is zero)
and sets
y to zero (since it uses the same storage location), causing
x and
y to lose their original values. ==Proof of correctness==