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.