Swapping variables is a very common operation used it tons of algorithms… like sorting. The most common and obvious technique is using a temporary variable to swap values between two variables:
{
int temp = i;
i = j;
j = temp;
}
Instead of writing a separate function for each data type, you could write a MACRO or templatize the function.
Swapping without using a temporary variable is an age old trick and there are a few ways to do this. You could use the basic arithmetic operations like +, -, /, *.
{
i = i + j;
j = i - j;
i = i - j;
}
The technique involves storing the sum of variables in one of them and then extracting it back by subtracting the other number. There are different variants to this technique… instead of starting by storing the sum, you could store the difference, product or the quotient. The last two could lead you to round-off and integer division errors. However all of them have one fundamental flaw. Its in line 3, and the issue is that this could lead to an overflow error.
This is another technique the gets you around these issues; the XOR Swapping Technique.
{
i = i ^ j;
j = j ^ i;
i = i ^ j;
}
This is an elegant technique and should work well with any primitive data type and you could write a simple MACRO like
Thanks to F.M.A.R. who sent me this article...
This is the pdf version of this article.