Wednesday, 24 February 2010

Programming puzzle

What does this code do?


int main(void)
{
int a = 123456;
int b = 654321;

printf("a = %d\nb = %d\n", a, b);

a = a ^ b;
b = b ^ a;
a = a ^ b;

printf("a = %d\nb = %d\n", a, b);
}


Last night my flatmate posed a programming puzzle and I solved it with the code above. Turning the problem on its head, what does the above code do?

Answer (highlight): Swaps a and b without using temporary
variable


PS: I expect this problem is as old as time itself...