< Previous | Contents | Next >

Passing a Constant Pointer

Youve seen that its possible to give a function access to variables by passing references. Its also possible to accomplish this using pointers. When you pass a pointer, you only pass the address of an object. This can be quite efficient, especially if youre working with objects that occupy large chunks of memory. Passing a pointer is like e-mailing a friend the URL of a website instead of trying to send him the entire site.

Before you can pass a pointer to a function, you need to specify function parameters as pointers. Thats what I do in the goodSwap() header.

void goodSwap(int* const pX, int* const pY)

This means that pX and pY are constant pointers and will each accept a memory address. I made the parameters constant pointers because, although I plan to change the values they point to, I dont plan to change the pointers themselves. Remember, this is just how references work. You can change the value to which a reference refers, but not the reference itself.

In main(), I pass the addresses of myScore and yourScore when I call goodSwap()

with the following line.

goodSwap(&myScore, &yourScore);

Notice that I send the addresses of the variables to goodSwap() by using the address of operator. When you pass an object to a pointer, you need to send the address of the object.

238 Chapter 7 n Pointers: Tic-Tac-Toe 2.0


In goodSwap(), pX stores the address of myScore and pY stores the address of yourScore. Anything done to *pX will be done to myScore; anything done to *pY will be done to yourScore.

The first line of goodSwap() takes the value that pX points to and assigns it to temp.

int temp = *pX;

Because pX points to myScore, temp becomes 150.

The next line assigns the value pointed to by pY to the object to which pX points.

*pX = *pY;

This statement copies the value stored in yourScore, 1000, and assigns it to the memory location of myScore. As a result, myScore becomes 1000.

The last statement in the function stores the value of temp, 150, in the address pointed to by pY.

*pY = temp;

Because pY points to yourScore, yourScore becomes 150.

After the function ends, control returns to main(), where I send myScore and yourScore to cout. This time, 1000 and 150 are displayed. The variables have exchanged values. Success at last!


Hi n t

image

You can also pass a constant pointer to a constant. This works much like passing a constant reference, which is done to efficiently pass an object that you don’t need to change. I’ve adapted the Inventory Displayer program from Chapter 6, which demonstrates passing constant references, to pass a constant pointer to a constant. 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 inventory_displayer_pointer_ver.cpp.

image