Skip to the content of the web site.

Swaps

One operation that is often necessary is to swap two values, be they two values in an array, or

There are many cute "tricks" that allow swaps to be performed using either addition and subtraction or the exclusive-or operation, but these are generally more expensive and the only possible benefit may be to not require one additional local variable, so this would only be useful and necessary if you are:

  • writing an embedded system, and
  • not calling a function.
#define SWAP( a, b )
do {
    (a) ^= (b);
    (b) ^= (a);
    (a) ^= (b);
} while ( false );

On the other hand, the standard way of swapping data is to

  1. temporarily store one of the variables,
  2. assign that variable the other variable, and
  3. assign the other variable the temporarily stored value.
    int a{ 42 };
    int b{ 91 };

    // Do something...

    // Swap the two variables
    int tmp{ a };
    a = b;
    b = tmp;

    // Continue...

Fortunately, however, there are two commands in the standard library that you should use:

#include <algorithm>

int main();

int main() {
    int a{ 42 };
    int b{ 91 };

    int array1[10]{  0,  1,  2,  3,  4,  5,  6,  7,  8,  9 };
    int array2[10]{ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };

    // Swap the two variables
    std::cout << a << ", " << b << std::endl;
    std::swap( a, b );
    std::cout << a << ", " << b << std::endl;

    // Swap two ranges
    //  - Swap array1[3], array1[4], array1[5]
    //    and  array2[5], array2[6], array2[7]
    std::swap_ranges( array1 + 3, array1 + 6, array2 + 5 );
    
    return 0;
}