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...

1 comment:

Peter said...

I expect, though my C knowledge remains a bit flaky, that it moves the contents of `a` to `b` and vice-versa. It's notable in that it does it somewhat in-place, without a temporary variable.