🔁 Swapping Two Numbers Using Bitwise XOR in C++
Swapping values of two variables is a common operation in programming. While many developers use a temporary variable or arithmetic operations, there is an efficient and clever method called the Bitwise XOR Swap. This technique swaps two variables using bitwise XOR operations — without requiring extra memory or arithmetic calculations.
The XOR method is particularly useful in memory-constrained environments or in embedded systems. It is also a popular topic in coding interviews, demonstrating a programmer’s understanding of low-level operations and binary logic.
💡 How XOR Swapping Works
XOR (Exclusive OR) is a binary operation that outputs 1 only when the inputs are different. It has a unique reversible property:
A = A ^ B B = A ^ B A = A ^ B
After these three operations, the values of A and B will be swapped, and no third variable is needed. Let’s see this implemented in C++.
📄 C++ Code Example
#include <iostream>
using namespace std;
int main() {
int firstNumber, secondNumber;
// Input from user
cout << "Enter the first number: ";
cin >> firstNumber;
cout << "Enter the second number: ";
cin >> secondNumber;
// Display before swapping
cout << "\nBefore Swapping:\n";
cout << "First Number = " << firstNumber << ", Second Number = " << secondNumber << endl;
// Swapping using Bitwise XOR
firstNumber = firstNumber ^ secondNumber;
secondNumber = firstNumber ^ secondNumber;
firstNumber = firstNumber ^ secondNumber;
// Display after swapping
cout << "\nAfter Swapping:\n";
cout << "First Number = " << firstNumber << ", Second Number = " << secondNumber << endl;
return 0;
}
✅ Sample Output
Enter the first number: 7 Enter the second number: 12 Before Swapping: First Number = 7, Second Number = 12 After Swapping: First Number = 12, Second Number = 7
📘 Definition: Swapping Using XOR
Swapping two numbers using Bitwise XOR is a technique where two variables exchange their values by applying XOR operations. This method uses three XOR steps to swap values without needing an extra variable. XOR swap is based on the reversible nature of XOR, making it an efficient and memory-safe way to perform swaps.
This method is especially suitable for low-level programming, embedded systems, and performance-critical code. It is a perfect example of using bit-level logic to solve basic programming problems more intelligently.
🧠 Final Thoughts
Swapping values without temporary storage showcases the power of bitwise operations. Whether you’re optimizing for memory, exploring efficient algorithms, or preparing for coding interviews, understanding XOR swap logic is a valuable skill.
Post a Comment