I was always fond of swapping numbers without a temporary variable like this.
void swap(int *a, int *b)
{
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
Today, I came to know that it does not work in all the cases, when I was doing swap(a+i, a+j), where a is an array and int i=j.
Sunday, February 04, 2007
Subscribe to:
Post Comments (Atom)
dude.. this overflows. use XOR instead
ReplyDeletea = a xor b
b = a xor b
a = a xor b
isn't this cool :)?
Even if you use XOR, the problem that I mentioned still remains. If both the variables point to the same location, then it does not work.
ReplyDeletewhy? it doesn't work?
ReplyDeleteProbably, you did not understand the actual problem.
ReplyDeleteTry this (XOR as well as addition/subtraction).
int a[1] = {3};
swap(&a[0], &a[0]);
printf("%d", a[0]);