< Previous | Contents | Next >
As you’ve seen, pointers can point to different objects at different times in a program. However, by using the const keyword when you declare and initialize a pointer, you can restrict the pointer so it can only point to the object it was initialized to point to. A pointer like this is called a constant pointer. Another way to say this is to say that the address stored in a constant pointer can never change—it’s constant. Here’s an example of creating a constant pointer:
int score = 100;
int* const pScore = &score; //a constant pointer
The preceding code creates a constant pointer, pScore, which points to score. You create a constant pointer by putting const right before the name of the pointer when you declare it.
Like all constants, you must initialize a constant pointer when you first declare it. The following line is illegal and will produce a big, fat compile error.
int* const pScore; //illegal - - you must initialize a constant pointer
Because pScore is a constant pointer, it can’t ever point to any other memory location. The following code is also quite illegal.
pScore = &anotherScore; //illegal – pScore can’t point to a different object
Although you can’t change pScore itself, you can use pScore to change the value to which it points. The following line is completely legal.
*pScore = 500;
232 Chapter 7 n Pointers: Tic-Tac-Toe 2.0
Confused? Don’t be. It’s perfectly fine to use a constant pointer to change the value to which it points. Remember, the restriction on a constant pointer is that its value—the address that the pointer stores—can’t change.
The way a constant pointer works should remind you of something—a reference. Like a reference, a constant pointer can refer only to the object it was initialized to refer to.
Hi n t
Although you can use a constant pointer instead of a reference in your programs, you should stick with references when possible. References have a cleaner syntax than pointers and can make your code easier to read.