Swap two numbers using bitwise XOR operator ^

We can swap two numbers using the XOR operator. The result of the bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It is denoted by ^. To know more about working of XOR, refer to this tutorial: https://youtu.be/zkQuKuITyYo

  #include<stdio.h>
  int main()
  {
   int x = 5, y = 10;

   printf("Before Swapping:\n");
   printf("X is %d, Y is %d\n",x,y);

   x = x^y ;
   y = x^y ;
   x = x^y ;

   printf("After Swapping:\n");
   printf("X is %d, Y is %d\n",x,y);

   return 0;
  }
x = x^y ;
y = x^y ;
x = x^y ;

It can also be written as,

x ^= y;
y ^= x;
x ^= y;

As the order of evaluation of XOR operator is from right to left, so this logic can be written in one line.

x ^= y ^= x ^= y;
How it works:

In this example,

x = 5, i.e., 0101 in binary

y = 10, i.e., 1010 in binary

therefore,

x = x^y; 0101^1010 = 1111 , i.e, 15 (x = 15)

y = x^y; 1111^1010 = 0101, i.e., 5. (y = 5)

x = x^y; 1111^0101 = 1010, i.e., 10, (x = 10)

Hence, we get, x = 10 and y = 5.

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.