< Previous | Contents | Next >

Introducing the Swap Program

The Swap program defines two variablesone that holds my pitifully low score and another that holds your impressively high score. After displaying the scores, the program calls a function meant to swap the scores. But because only copies of the score values are sent to the function, the argument variables that hold the scores are unchanged. Next, the program calls another swap function. This time, through the use of references, the argument variablesvalues are successfully exchangedgiving me the great big score and leaving you with the small one. Figure 6.2 shows the program in action.

192 Chapter 6 n References: Tic-Tac-Toe



image

Figure 6.2

Passing references allows goodSwap() to alter the argument variables.


You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 6 folder; the filename is swap.cpp.

// Swap

// Demonstrates passing references to alter argument variables #include <iostream>

using namespace std;


void badSwap(int x, int y); void goodSwap(int& x, int& y);


int main()

{

int myScore = 150; int yourScore = 1000;

cout << "Original values\n";

cout << "myScore: " << myScore << "\n";

cout << "yourScore: " << yourScore << "\n\n";

Passing References to Alter Arguments 193


cout << "Calling badSwap()\n"; badSwap(myScore, yourScore);

cout << "myScore: " << myScore << "\n";

cout << "yourScore: " << yourScore << "\n\n";


cout << "Calling goodSwap()\n"; goodSwap(myScore, yourScore);

cout << "myScore: " << myScore << "\n"; cout << "yourScore: " << yourScore << "\n";


return 0;

}


void badSwap(int x, int y)

{

int temp = x; x = y;

y = temp;

}


void goodSwap(int& x, int& y)

{

int temp = x; x = y;

y = temp;

}