Last Updated: February 25, 2016
·
226
· alexcristea

Swap two variables values

Let's say that we have two variables a and b and we want to swap their values:

int a = 5;
int b = 9;

In a classical fashion we usually use an temporary tmp variable to help us do the trick:

int tmp = a;     // tmp = 5
a = b;           // a = 9
b = tmp;         // b = 5

This is also possible without using tmp. We only have to do some XOR bit operations:

a = a xor b;      // a = 12
b = a xor b;      // b = 5
a = a xor b;      // a = 9

Read the full article on http://betterexplained.com.