Posts tagged XOR bit-wise operation to swap two variables
How to swap two integers without using third variable
Nov 13th
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: More > 

Recent Comments