Using const with Pointers in C++

A constant pointer points to a constant memory location, but the actual value in the memory location can be changed.

You have learned how to declare a constant using the const keyword. Once it is declared, a constant cannot be changed. You can declare a constant pointer. For example:

double radius = 5;

double* const p = &radius;

Here p is a constant pointer. It must be declared and initialized in the same statement. You cannot assign a new address to p later. Though p is a constant, the data pointed to by p is not constant. You can change it. For example, the following statement changes radius to 10:

*p = 10;

Can you declare that dereferenced data be constant? Yes. You can add the const keyword in front of the data type, as follows:

In this case, the pointer is a constant, and the data pointed to by the pointer is also a constant.

If you declare the pointer as

const double* p = &radius;

then the pointer is not a constant, but the data pointed to by the pointer is a constant.

For example:

double radius = 5;

double* const p = &radius;

double length = 5;

*p = 6; // OK

p = &1ength; // Wrong because p is constant pointer

 

const double* p1 = &radius;

*p1 = 6; // Wrong because p1 points to a constant data

p1 = &length; // OK

 

const double* const p2 = &radius;

*p2 = 6; // Wrong because p2 points to a constant data

p2 = &length; // Wrong because p2 is a constant pointer

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *