- Write a program in C to swap two variables using Xor bitwise operator.
- How to swap two variables in C using bitwise operators.
Algorithm to swap two numbers using Xor bitwise operator
- Here is the basic algorithm to swap two variables without using a temporary third variable. Let A and B are two variable:
- A = A + B
- B = A - B;
- A = A - B;
- Bitwise Xor of A and B(A^B) is equivalent to sum of A and B(A+B). Hence algorithm can be re-written in terms of Xor operator as:
- A = A ^ B
- B = A ^ B;
- A = A ^ B;
C program to swap two variable using Xor bitwise operator.
#include<stdio.h> int main() { int a, b; printf("Enter the value of A and B\n"); scanf("%d %d", &a, &b); /* swap two variables */ a = a ^ b; b = a ^ b; a = a ^ b; // Equivalent one liner : x ^= y ^= x ^= y; printf("After Swapping, A = %d, B = %d", a, b); return 0; }Output
Enter the value of A and B 3 7 After Swapping, A = 7, B = 3