79831837

Date: 2025-11-27 15:27:40
Score: 0.5
Natty:
Report link

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:


1. Using arithmetic operations

a = a + b;
b = a - b;
a = a - b;

Pros:

Cons:


2. Using XOR (bitwise swap)

a = a ^ b;
b = a ^ b;
a = a ^ b;

Pros:

Cons:


3. Using std::swap (recommended)

std::swap(a, b);

Pros:

Cons:

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Nitesh Kumar