This equation swaps two numbers without a temporary variable, but uses arithmetic operations:
a = (a+b) - (b=a);
How can I do it without ar
Multiplication and division can also be used.
int x = 10, y = 5;
// Code to swap 'x' and 'y'
x = x * y; // x now becomes 50
y = x / y; // y becomes 10
x = x / y; // x becomes 5
C++11
allows to:
Swap values:
std::swap(a, b);
Swap ranges:
std::swap_ranges(a.begin(), a.end(), b.begin());
Create LValue tuple with tie:
std::tie(b, a) = std::make_tuple(a, b);
std::tie(c, b, a) = std::make_tuple(a, b, c);
a=a+b;
b=a-b;
a=a-b;
This is simple yet effective....
In C this should work:
a = a^b;
b = a^b;
a = a^b;
OR a cooler/geekier looking:
a^=b;
b^=a;
a^=b;
For more details look into this. XOR is a very powerful operation that has many interesting usages cropping up here and there.