Swapping is commonly used when we have two variables, and need to make sure if one is greater than another. The most commonly used Swap Algorithm is as below:

**Third Variable**

void Swap(int& a, int& b){
int tmp = a;
a = b;
b = tmp;
}

What if, although it’s not really possible, that you have not enough memory for a `tmp`

variable? Now, the following Swap Algorithm comes in handy:

**Binary Operation**

void Swap(int& a, int& b){
a = a + b;
b = a - b; // b = (a+b) - b
a = a - b; // a = (a+b) - [(a+b) - b]
}

Algorithms has pros and cons too. While using Binary Operation can save you one-variable memory, it is not save to use in data types such as `float`

or `double`

. This is because the round off error while doing the binary operations will destroy the actual value of the variables.

### Like this:

Like Loading...

*Related*