Swapping the contents of two variables is a common sub-problem. It is, for example, one step in many sorting algorithms. Imagining the swapping problems as two glasses can help us better understand the necessary steps in a programming solution.
Before the swap
After the swap
The swapping problem visualized as two glasses. To help us discuss the problem, we make the glasses different shapes: one is tall and narrow, and the other is short and wide. We must further assume that the two glasses have the same volume despite their different shapes. The pictures help us understand that we can't simply pour the contents of one glass into the other - doing so would over-fill one glass and mix the two liquids.
Swapping the contents of two glasses. We need a third temporary glass (i.e., variable) to solve the swapping problem with glasses. Given a temporary glass, we can solve the problem in three steps:
The temporary glass is initially empty so that we can pour the contents of the wide glass into it
Now, the wide glass is empty, and we can pour the contents of the tall glass into the wide glass
Finally, the tall glass is empty, and we can pour the contents of the temporary glass into the tall glass
The results of step 3 match the "After the swap" picture in Figure 1 - the desired solution. The temporary glass is no longer needed, and we can discard it.
It may seem improbable that glasses filled with liquid could be related to a programming problem. Nevertheless, glasses are tangible, and most of us have some experience with them. Alternatively, computer programs are intangible and abstract - not something we can hold and turn in our hands - and something that many of you have only experienced a little. The analogy gives us something more concrete, less abstract, something more familiar with which to work. Some of you may be surprised at how close the programming solution is to the steps outlined above.
Swapping the contents of two variables. The example uses T as a general or unspecified data type. It serves as a placeholder while illustrating the swapping algorithm's pattern and emphasizes that the three variables must be the same type. In a "real" program, we can replace T with a fundamental data type like int or double, or the name of a structure (chapter 5) or class (chapter 9). Ellipses denote code removed for simplicity.
Defines and initializes two variables of an unspecified type, T. The only requirement is the type must support the assignment operation.
A simple variable can only save one value at a time. So, the swapping algorithm needs a temporary variable, temp. After saving the current contents of x2 in temp, x2 is "empty" and available to receive the contents of x1. Now, x1 is "empty" and available to receive the contents of temp, completing the swap operation.