Swap without temporary variable

This tip submitted by Moosa Baransi on 2013-03-01 04:52:27. It has been viewed 5000 times.
Rating of 5.2 with 68 votes



You can swap between two variable using the XOR operation as shown below:

int a=5, b=-3;
a ^= b ^= a ^= b;
printf("a = %d, b = %d\n", a, b);

Explanation:
Assume a = x, b = y;

The order of the XOR is right to left, so we will start from right:
a ^= b --> a = x ^ y
b ^= a --> b = y ^ (x ^ y) = x
a ^= b --> a = x ^ y ^ x = y



More tips

Help your fellow programmers! Add a tip!