Swapping two variables without using a temp variable
Using pointers
#include <stdio.h>
void change(int *,int*);
int main ()
{
int a=2,b=5;
printf("Before : a=%d,b=%d\n",a,b);
change(&a,&b);
printf("After : a=%d,b=%d\n",a,b);
return 0;
}
void change(int *a,int *b){
*a += *b;
*b = *a-*b;
*a = *a-*b;
}
Results
Before : a=2,b=5
After : a=5,b=2
Making use of a Macro
#include <stdio.h>
#define SWAP(x,y) x ^= y, y ^= x, x ^= y
int main ()
{
int a=2,b=5;
printf("Before : a=%d,b=%d\n",a,b);
SWAP(a,b);
printf("After : a=%d,b=%d\n",a,b);
return 0;
}
Results
Before : a=2,b=5
After : a=5,b=2
Note that:
The name of the macro or variables may be changed to your convenience.