C++ Swap 2 Variables Without Using 3rd Variable
To swap two variables without using a third variable in C++, you can use the XOR bitwise operator. Here are the steps to accomplish this:
- Initialize two variables, let's say
a
andb
, with their respective values. - XOR
a
withb
and store the result ina
. This step effectively combines the bits ofa
andb
without any loss of information. - XOR the new value of
a
with the original value ofb
and store the result inb
. This step effectively reverses the XOR operation, resulting in the original value ofa
being stored inb
. - XOR the new value of
b
with the new value ofa
and store the result ina
. This step effectively reverses the XOR operation again, resulting in the original value ofb
being stored ina
.
After these steps, the values of a
and b
will be swapped. Let's see an example code snippet to demonstrate this:
#include <iostream>
int main() {
int a = 5;
int b = 10;
std::cout << "Before swapping: a = " << a << ", b = " << b << std::endl;
a = a ^ b;
b = a ^ b;
a = a ^ b;
std::cout << "After swapping: a = " << a << ", b = " << b << std::endl;
return 0;
}
In this example, we initialize a
with a value of 5 and b
with a value of 10. After swapping, the value of a
becomes 10 and the value of b
becomes 5.