Swap without temporary variableThis tip submitted by Moosa Baransi on 2013-03-01 04:52:27. It has been viewed 3793 times.
Rating of 4.1 with 40 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);
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
Help your fellow programmers! Add a tip!