How to swap two integers without using third variable
The safest way to swap two variables without using third variable is to use XOR operation as shown below.
This example C program swaps integer values of two variables i and j.
[neo@techpulp ~]# cat iswap.c
#include <stdio.h>
int main(int argc, char *argv[])
{
int i = 10, j = 20;
printf("Before swap: i = %d, j = %d\n", i, j);
i = i^j;
j = i^j;
i = i^j;
printf("After swap: i = %d, j = %d\n", i, j);
return 0;
}
[neo@techpulp ~]# gcc iswap.c -o iswap
[neo@techpulp ~]# ./iswap
Before swap: i = 10, j = 20
After swap: i = 20, j = 10
[neo@techpulp ~]#
The same can be achieved using multiplication, division and subtraction operations bu they are not safe as integer overflow or underflow may occur.

