Swap (computer programming)

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):

data_item x := 1
data_item y := 0

swap (x, y);

After swap() is performed, x will contain the value 0 and y will contain 1; their values have been exchanged. This operation may be generalized to other types of values, such as strings and aggregated data types. Comparison sorts use swaps to change the positions of data.

In many programming languages the swap function is built-in. In C++, overloads are provided allowing std::swap to exchange some large structures in O(1) time.