How do we swap values of two integer variables?

Normally we will introduce a third variable as the temporay storage. For example in C/C++:

int a = 123456;

int b = 567890;

int temp;

```
```

`temp = a;`

a = b;

b = temp;

Ok the question now is: How do we swap values of two integer variables without third variable?

Here is the trick:

int a = 123456;

int b = 567890;

```
```

`a ^= b;`

b ^= a;

a ^= b;

Don’t believe? You can try it out yourself.

Note:

- only for integer values (eg. 8, 16, 32, 64 bits integers)
`^`

means eXclusive OR (XOR)

Explaination:

When a value is XOR with another value, the result is actually “storing” value of two values. When one of the original value is XOR again with the result value, you will get the another value. For example:

int a = 123;

int b = 456;

int resultOfXOR;

```
```resultOfXOR = a ^ b; // "storing" 2 values

`resultOfXOR ^ a; // return value of b`

resultOfXOR ^ b; // return value of a

From the above code

int a = 123456;

int b = 567890;

```
```a ^= b; // storing **a^b** into **a**. **a** becomes result of XOR

b ^= a; // get value of original **a** by **resultOfXOR^b** and store into **b**. Now b = 123456.

a ^= b; // get value of original **b** by **resultOfXOR^b** and store into **a**. Now a = 567890.

`// Finally b = 123456 and a = 567890`

That’s the beauty of XOR.

Kuzco says

awesome!

mypapit says

nice article, I’m not aware that we can do that with XOR