You can swap two integers in C++ without using a third variable in several ways, but each method has caveats. Here are the common approaches:
a = a + b;
b = a - b;
a = a - b;
Pros:
Cons:
a + b exceeds the integer limit.a = a ^ b;
b = a ^ b;
a = a ^ b;
Pros:
No overflow issues.
Does not require extra space.
Cons:
Does not work if a and b refer to the same memory location (e.g., swapping the same variable).
Less readable than normal swap.
std::swap (recommended)std::swap(a, b);
Pros:
Most readable and safest method.
Modern compilers optimize it very well.
Cons: