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:

  1. Initialize two variables, let's say a and b, with their respective values.
  2. XOR a with b and store the result in a. This step effectively combines the bits of a and b without any loss of information.
  3. XOR the new value of a with the original value of b and store the result in b. This step effectively reverses the XOR operation, resulting in the original value of a being stored in b.
  4. XOR the new value of b with the new value of a and store the result in a. This step effectively reverses the XOR operation again, resulting in the original value of b being stored in a.

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.