< Previous | Contents | Next >

Using a Pointer to a

Constant

As youve seen, you can use pointers to change the values to which they point. However, by using the const keyword when you declare a pointer, you can restrict a pointer so it cant be used to change the value to which it points. A pointer like this is called a pointer to a constant. Heres an example of declaring such a pointer:

const int* pNumber; //a pointer to a constant

The preceding code declares a pointer to a constant, pNumber. You declare a pointer to a constant by putting const right before the type of value to which the pointer will point.

You assign an address to a pointer to a constant as you did before.

int lives = 3; pNumber = &lives;

However, you cant use the pointer to change the value to which it points. The following line is illegal.

*pNumber -= 1; //illegal - - can’t use pointer to a constant to change value

//that pointer points to

Although you cant use a pointer to a constant to change the value to which it points, the pointer itself can change. This means that a pointer to a constant

Understanding Pointers and Constants 233


can point to different objects in a program. The following code is perfectly legal.

const int MAX_LIVES = 5;

pNumber = &MAX_LIVES; //pointer itself can change