< Previous | Contents | Next >

Using a Constant Pointer to a Constant

A constant pointer to a constant combines the restrictions of a constant pointer and a pointer to a constant. This means that a constant pointer to a constant can only point to the object that it was initialized to point to. In addition, it cant be used to change the value of the object to which it points. Heres the declaration and initialization of such a pointer:

const int* const pBONUS = &BONUS; //a constant pointer to a constant

The preceding code creates a constant pointer to a constant named pBONUS that points to the constant BONUS.


Hin t

image

Like a pointer to a constant, a constant pointer to a constant can point to either a non-constant or constant value.

image


You cant reassign a constant pointer to a constant. The following line is not legal.

pBONUS = &MAX_LIVES; //illegal - - pBONUS can’t point to another object

You cant use a constant pointer to a constant to change the value to which it points. This means that the following line is illegal.

*pBONUS = MAX_LIVES; //illegal - - can’t change value through pointer

In many ways, a constant pointer to a constant acts like a constant reference, which can only refer to the value it was initialized to refer to and which cant be used to change that value.


Hin t

image

Although you can use a constant pointer to a constant instead of a constant reference in your programs, you should stick with constant references when possible. References have a cleaner syntax than pointers and can make your code easier to read.

image

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