Sunday, February 04, 2007

Swapping without temporary variables

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.

4 comments:

  1. dude.. this overflows. use XOR instead

    a = a xor b
    b = a xor b
    a = a xor b

    isn't this cool :)?

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

    ReplyDelete
  3. why? it doesn't work?

    ReplyDelete
  4. Probably, you did not understand the actual problem.

    Try this (XOR as well as addition/subtraction).

    int a[1] = {3};
    swap(&a[0], &a[0]);
    printf("%d", a[0]);

    ReplyDelete