language-icon Old Web
English
Sign In

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): 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): 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. The simplest and probably most widely used method to swap two variables is to use a third temporary variable:

[]
Parent Topic
Child Topic
    No Parent Topic