< Previous | Contents | Next >
Introducing the Swap Pointer Version
The Swap Pointer Version program works just like the Swap program from Chapter 6, except that the Swap Pointer Version program uses pointers instead of references. The Swap Pointer Version program defines two variables—one
Passing Pointers 235
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. Because only copies of the score values are sent to the function, the original variables are unaltered. Next, the program calls another swap function. This time, through the use of constant pointers, the original variables’ values are successfully exchanged (giving me the great big score and leaving you with the small one). Figure 7.3 shows the program in action.
Figure 7.3
Passing pointers allows a function to alter variables outside of the function’s scope.
You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 7 folder; the filename is swap_pointer_ver.cpp.
// Swap Pointer
// Demonstrates passing constant pointers to alter argument variables #include <iostream>
using namespace std;
void badSwap(int x, int y);
void goodSwap(int* const pX, int* const pY);
int main()
{
236 Chapter 7 n Pointers: Tic-Tac-Toe 2.0
int myScore = 150; int yourScore = 1000;
cout << "Original values\n";
cout << "myScore: " << myScore << "\n";
cout << "yourScore: " << yourScore << "\n\n";
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* const pX, int* const pY)
{
//store value pointed to by pX in temp int temp = *pX;
//store value pointed to by pY in address pointed to by pX
*pX = *pY;
//store value originally pointed to by pX in address pointed to by pY
*pY = temp;
}