«Consider yourself Perfectible makes you Perfect!»
Swap the value of two integers without temporary storage
Someone says this is an old lame trick. I think it’s simple and clever use of XOR.
How/Why does it work?
It’s built around the properties of the XOR ^ operator, who has the following properties:
A ^ B = B ^ A(commutative)A ^ 0 = AA ^ 1 = ~AA ^ A = 0
So, you can see how it get’s applied here:
#include <stdio .h>
int main(void)
{
unsigned int a, b;
// ... populate somehow "a" and "b"...
printf("a = %d - b = %d\n", a, b);
a ^= b; // store in "a" the value of "a XOR b"
b ^= a; // store in "b" the value of "a XOR b XOR b" = "a XOR 0" = "a"
a ^= b; // store in "a" the velue of "a XOR b XOR a" = "b XOR 0" = "b"
printf("a = %d - b = %d\n", a, b);
}
Neat.
| Print article | This entry was posted by Detro on Wed 13 January, 2010 at 21:48, and is filed under Personal. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |

about 7 months ago
What about:
a+=b;
b=a-b;
a-=b;
Or just for fun:
a*=b;
b=a/b;
a/=b;
But of course, you would never use * and / this way
about 7 months ago
Yes, but I think this can suffer of overflow if “a” or “b” are too big.
But very nice indeed.