Posts tagged ‘integer swap’

## How to swap two integers in C++

Warning: this post got embarrassingly long. For the short version, read up through the paragraph that starts with “If you use.”

This is something that’s been bugging me for a while, and I’d like to lay it to rest. If you’ve done any work in C++, you’ve probably heard the riddle about how to swap two integers without using a temporary variable. The question is exactly what it sounds like: you have two integers (call them `x` and `y`), you want to swap their values, and you may or may not want to use a third, temporary variable while doing it. Here are some ways of swapping integers that I have actually seen in professional code written by professional coders:

Method Name Code
Method A
```{  // Limit the scope of t
int t = x;
x = y;
y = t;
}```
Method B
```x ^= y;
y ^= x;
x ^= y;```
Method C
`x ^= y ^= x ^= y;`
Method D
```x = x + y;
y = x - y;
x = x - y;```
Method E
`std::swap(x, y);`

Which of these is the fastest way to swap integers? Which way is the fastest method that doesn’t require extra memory? When will you want to use a different method? What is the overall best method?