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
Using XOR,
void swap(int &a, int &b)
{
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
One liner with XOR,
void swap(int &a, int &b)
{
a ^= b ^= a ^= b;
}
These methods appear to be clean, because they don't fail for any test-case, but again since (as in method 2) value of variable is modified twice within the same sequence point, it is said to be having undefined behavior declared by ANSI C.