XORswap
XORswap, or the XOR swap trick, is a technique for swapping the values of two variables without using a temporary storage location. It relies on the bitwise exclusive OR operation to rearrange bits so that the original values are exchanged through a three-step sequence.
A common implementation uses three statements in this order: a = a ^ b; b = a ^ b; a
But XORswap has notable drawbacks. If a and b refer to the same memory location (aliases), the
In contemporary programming, the standard approach—using a temporary variable or a language-provided swap construct (for example,