How to swap variables in C or C++

A third variable

The best option to swap two variables is to use a third temporary variable:

int temp = a;
a = b;
b = temp;

A function for swapping

If a function is required for swapping variable, the same mecanisme can be used in the function with pointers:

// Swap a and b
void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

Other (bad) options

We can find on the web some other options that do not require a third variable. The following is one of the most common :

a = a + b;
b = a - b;
a = a - b;

This options work with integers, but is not a good idea. First of all, additions and substractions are slower than assignment. So the previous code is probably slower than using a third temporary variable.

The second problem is that this option do not always work with floats. When adding a large floatting number with a smaller one, the result can be approximated due to the way floatting numbers are encodded in binary. The following code shows a non-working solution:

In the same way, we sometime find this function for swapping variables:

void swap(int* a, int* b)
{
    *a ^= *b;
    *b ^= *a;
    *a ^= *b;
}

The previous function does not work if a and b are at the same address. The first XOR will clear all of the bits at the memory address pointed and the function will return 0 for both address.

Conclusion

In conclusion, there is only good option, using a temporary variable :

int temp = a;
a = b;
b = temp;

or, if you need a function:

void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

See also


Last update : 05/23/2022