Swap two integers using a temporary variable, using std::swap, and using arithmetic without a temporary.
#include <iostream>
#include <utility>
int main() {
int a = 10, b = 25;
int temp = a; // 1. temporary variable
a = b;
b = temp;
std::cout << "temp: a=" << a << " b=" << b << '\n';
std::swap(a, b); // 2. standard library
std::cout << "std::swap: a=" << a << " b=" << b << '\n';
a = a + b; // 3. arithmetic (can overflow for large values)
b = a - b;
a = a - b;
std::cout << "no temp: a=" << a << " b=" << b << '\n';
return 0;
}
temp: a=25 b=10 std::swap: a=10 b=25 no temp: a=25 b=10
std::swap from <utility> is the idiomatic choice and works for any type. The arithmetic trick is an interview favourite but can overflow, so avoid it in real code.