Programming Tutorials and Interview Questions

Swapping two numbers using bitwise operator XOR is a programming trick that is usually asked in technical interviews. It does not use a third temp variable for swapping values between two variables. This solution only works for unsigned integer types. It won't work for floating point, pointers, and struct/union types.

Here, we are using XOR (`^`

) operator to swap two integers. If you don't get confused the XOR operator returns the second number if the result of two XOR-ed numbers is again XOR-ed with first original number, and returns the first number if the result of two XOR-ed numbers is again XOR-ed with second original number.

Now let's understand it by an example, imagine we have two numbers 5 and 7. The XOR of 5 and 7 (`5 ^ 7`

) will be 2, further, if we XOR 2 with 5, we will get 7 or if we XOR 2 with 7 we will get 5. This trick helps in swapping the numbers.

In the following C program we swap the values of two variables by XORing these variables with each other. We have `n1 = 5`

and `n2 = 7`

. In first step, we do `n1 = n1 ^ n2;`

which results `2`

. This result is stored back in `n1`

. In second step, we do `n2 = n1 ^ n2;`

that is `2 ^ 7`

. It will return `5`

, which gets assigned to `n2`

. So, till now one number got swapped. In third step, we do `n1 = n1 ^ n2;`

that is `2 ^ 5`

. It will return `7`

, which gets assigned to `n1`

. Hereby, `n1`

and `n2`

are swapped.

/* C program to swap two integers using bitwise operators */ #include <stdio.h> int main() { int n1 = 5, n2 = 7; printf("Before swap: n1: %d \t n2: %d\n", n1, n2); n1 = n1 ^ n2; n2 = n1 ^ n2; n1 = n1 ^ n2; printf("After swap: n1: %d \t n2: %d\n", n1, n2); return 0; } OUTPUT ====== Before swap: n1: 5 n2: 7 After swap: n1: 7 n2: 5

Following is another C program that swaps two numbers using arithmetic operators without using a third temp variable.

/* C program to swap two integers using bitwise operators */ #include <stdio.h> int main() { int n1 = 5, n2 = 7; printf("Before swap: n1: %d \t n2: %d\n", n1, n2); n1 = n1 + n2; n2 = n1 - n2; n1 = n1 - n2; printf("After swap: n1: %d \t n2: %d\n", n1, n2); return 0; } OUTPUT ====== Before swap: n1: 5 n2: 7 After swap: n1: 7 n2: 5

Hope you have enjoyed reading this C program swapping two integers using bitwise XOR operator. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!

Researchers say the WannaCry ransom note was poorly translated - possibly using Google Translate.

Chief executive Alex Cruz says flight disruption at Heathrow and Gatwick had nothing to do with cost cutting.

Delivering a lecture at the Hay Festival, the actor said society could face "dire consequences".