C# swapping values

We have always learned that swapping values in programming is easily done by having a 'helper' value.

Because if you do not use a helper value you will get the following problem:

c#:
{
a = 1;
b = 2;

a = b; // a now holds 2
b = a; // b now also holds 2 -> not what we want.
}

When using a 'helper' value this will work better, like this:

c#:
{
a = 1;
b = 2;

// swap values:
temp = a; // temp to hold 1
a = b; // a now holds 2
b = temp; // b now holds 1
}

But still, do we actually NEED a helper value?

It turns out we do not have to use it, if we make use of some simple mathematic characteristics.

c#:
{
// swap without temp value:
int a = 1;
int b = 2;

a = a + b; // 1 + 2 = 3 (a holds the total)
b = a – b; // 3 – 2 = 1 (b now holds original value of a)
a = a – b; // 3 – 1 = 2 (total minus original value of a gives original value of b)

}

This will of course also work for doubles/floats. But be carefull for overflows though 🙂