< Previous | Contents | Next >

Using a Constant Pointer

As youve 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 changeits constant. Heres 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 cant 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 cant 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? Dont be. Its 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 valuethe address that the pointer storescant change.

The way a constant pointer works should remind you of somethinga reference. Like a reference, a constant pointer can refer only to the object it was initialized to refer to.


Hi n t

image

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.

image