In computer programming, the act of swapping two variables refers to mutually exchanging the values of the variables. Usually, this is done with the data in memory. For example, in a program, two variables may be defined thus (in pseudocode):
(In many programming languages where the swap function is built-in; in C++, overloads are provided allowing std::swap to swap some large structures in O(1) time.) After swap() is performed, x will contain the value 0 and y will contain 1; their values have been exchanged. Of course, this operation may be generalized to other types of values, such as strings, aggregated data types and comparison sorts, utilize swaps to change the positions of data.
The simplest and probably most widely used method to swap two variables is to use a third temporary variable:
While this is conceptually simple and in many cases the only convenient way to swap two variables, it uses extra memory. Although this should not be a problem in most applications, the sizes of the values being swapped may be huge (which means the temporary variable may occupy a lot of memory as well), or the swap operation may need to be performed many times, as in sorting algorithms.
In addition, swapping two variables in object-oriented languages such as C++ may involve one call to the class constructor and destructor for the temporary variable, and three calls to the copy constructor. Some classes may allocate memory in the constructor and deallocate it in the destructor, thus creating expensive calls to the system. Copy constructors for classes containing a lot of data, e.g. in an array, may even need to copy the data manually.