Swap using XOR
Swap Two Numbers using XOR in C++
IntermediateTopic: Bitwise Operations Programs
C++ Swap using XOR Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
using namespace std;
void swapXOR(int& a, int& b) {
a = a ^ b;
b = a ^ b; // b = (a^b) ^ b = a
a = a ^ b; // a = (a^b) ^ a = b
}
int main() {
int a = 10, b = 20;
cout << "Before swap: a = " << a << ", b = " << b << endl;
swapXOR(a, b);
cout << "After swap: a = " << a << ", b = " << b << endl;
// Multiple swaps
cout << "\nMultiple swaps:" << endl;
int x = 5, y = 15, z = 25;
cout << "Before: x = " << x << ", y = " << y << ", z = " << z << endl;
swapXOR(x, y);
swapXOR(y, z);
cout << "After: x = " << x << ", y = " << y << ", z = " << z << endl;
// XOR properties demonstration
cout << "\nXOR properties:" << endl;
int num1 = 12, num2 = 25;
cout << "num1 = " << num1 << ", num2 = " << num2 << endl;
cout << "num1 ^ num2 = " << (num1 ^ num2) << endl;
cout << "(num1 ^ num2) ^ num2 = " << ((num1 ^ num2) ^ num2) << " (back to num1)" << endl;
cout << "(num1 ^ num2) ^ num1 = " << ((num1 ^ num2) ^ num1) << " (back to num2)" << endl;
return 0;
}Output
Before swap: a = 10, b = 20 After swap: a = 20, b = 10 Multiple swaps: Before: x = 5, y = 15, z = 25 After: x = 15, y = 25, z = 5 XOR properties: num1 = 12, num2 = 25 num1 ^ num2 = 21 (num1 ^ num2) ^ num2 = 12 (back to num1) (num1 ^ num2) ^ num1 = 25 (back to num2)
Understanding Swap using XOR
XOR swap: a = a^b, b = a^b (which is a), a = a^b (which is b). No temporary variable needed. Works because: (a^b)^b = a and (a^b)^a = b. Note: Don't use if variables point to same memory location. Useful in embedded systems with limited memory.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.