Adrian Lita

Swapping numbers without the third variable

By: Adrian Lita

Published on: 2018-06-12

Keywords: #swapping #variables #academic #snippet #xorswap #xor


While not recommeded to be used in modern programming, this simple method allows swapping the values of 2 variables without the need of the third. Some caution should be taken into consideration, because this method works as long as both the variables that needed to be swapped are different (read: occupy different memory). void xorSwap(int *a, int *b) { *a = *a ^ *b; *b = *b ^ *a; *a = *a ^ *b; } This is the simplest variant of the xorSwap. Several...

Read More >