Swapping Without Temp Variable

Swapping values with subtraction and addition

#define SWAP(a, b) ((&(a) == &(b)) || \
                    (((a) -= (b)), ((b) += (a)), ((a) = (b) - (a))))

This swaps the values of a and b without using a temporary variable. The initial check for a and b being the same location in memory may be omitted when you know this can't happen. (The compiler may omit it anyway as an optimization.) The XOR method that follows may be slightly faster on some machines.
Sanjeev Sivasankaran suggested I add this on June 12, 2007.

Swapping values with XOR

#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))

This is an old trick to exchange the values of the variables a and b without using extra space for a temporary variable.
On January 20, 2005, Iain A. Fleming pointed out that the macro above doesn't work when you swap with the same memory location, such as SWAP(a[i], a[j]) with i == j. So if that may occur, consider defining the macro as (((a) == (b)) || (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))).

Source:
http://graphics.stanford.edu/~seander/bithacks.html#OperationCounting

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License