1. method 1
#include <stdio.h>
void swap(int* xp, int* yp)
{
if (xp == yp) // Check if the two addresses are same
return;
*xp = *xp + *yp;
*yp = *xp - *yp;
*xp = *xp - *yp;
}
int main()
{
int x = 10;
swap(&x, &x);
printf("After swap(&x, &x): x = %d", x);
return 0;
}
2. method 2
#include <stdio.h>
void swap(int* xp, int* yp)
{
if (xp == yp)
return;
*xp = *xp ^ *yp;
*yp = *xp ^ *yp;
*xp = *xp ^ *yp;
}
int main()
{
int x = 10;
swap(&x, &x);
printf("After swap(&x, &x): x = %d", x);
return 0;
}
NOTE: the check for xp == yp is necessary, if they point to same variable, the algorithm will not work.
For macro,
#define swap(a,b) ({\
if (a != b) {\
(*a) = (*a) ^ (*b);\
(*b) = (*a) ^ (*b);\
(*a) = (*a) ^ (*b);\
}\
})