The bitwise XOR operator can be used to swap two variables. Here the concept is that EX-OR of two same numbers is zero. The XOR of two numbers a and b returns a number which has all the bits as 1 wherever bits of a and b differ.
#include <stdio.h>
int main()
{
int a, b ;
printf("Enter Value of a = ");
scanf("%d", &a);
printf("Enter Value of b = ");
scanf("%d", &b);
a = a ^ b; // a now becomes 30
b = a ^ b; // b becomes 10
a = a ^ b; // a becomes 20
printf("After Swapping: a = %d, b = %d", a, b);
return 0;
}
Output:
Enter Value of a = 10
Enter Value of b = 20
After Swapping: a = 20, b = 10
need an explanation for this answer? contact us directly to get an explanation for this answer