  in computer programming, the xor swap is an algorithm that uses the xor bitwise operation to swap values of distinct variables having the same data type without using a temporary variable. "distinct" means that the variables are stored at different memory addresses; the actual values of the variables do not have to be different. ==the algorithm== 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 := x xor y y := x xor y x := x xor y the algorithm typically corresponds to three machine code instructions. since xor is a commutative operation, x xor y can be replaced with y xor x in any of the lines. when coded in assembly language, this commutativity is often exercised in the second line: {| class="wikitable" style="width: 45em;" |- ! pseudocode !! ibm system/370 assembly !! x86 assembly |- |  ||  ||  |- |  ||  ||  |- |  ||  ||  |} in the above system/370 assembly code sample, r1 and r2 are distinct registers, and each xr 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. however, 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". note that 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== the binary operation xor over bit strings of length n exhibits the following properties (where \oplus den
Algorithms Binary_arithmetic