Hello, I’m Liang Tang.

This is part 28 of the EasyC++ series on Pointers and const.

If you want a better reading experience, you can visit the Github repository.

Pointers and const

We know that the const keyword modifies immutable variables, and there are many subtleties to using it with Pointers.

There are two different ways of decorating Pointers with const. The first is to have a pointer to a constant object, which prevents the pointer from being used to modify the value it points to. The second is to declare the pointer itself as a constant, which prevents the position of the pointer from changing. Now let’s look at the details.

Pointer to a constant

The first is a pointer to a constant, meaning that the type of the pointer is a constant. So write:

const int * p;
Copy the code

P is a pointer that is of type const int. It can be used to refer to either a constant type or a nonconstant type, both of which are legal:

int age = 23;
const int* p = &age;

const double price = 233;
const double* pt = &price;
Copy the code

But conversely, it is illegal to assign a const to a pointer that is not const:

const int age = 23;
int* p = &age;	/ / illegal
Copy the code

If you have to do this, you can cast it using the CONST_cast operator, which we will discuss in a later article.

If we assign a nonconst to a pointer to const, we can change the value through the pointer, but we can change the value through the variable:

int age = 23;
const int* p = &age;

*p = 233;	/ / illegal
age = 233;	/ / legal
Copy the code

Also, we cannot change the value of the pointer, but we can change the position of the pointer:

int age = 23;
int price = 233;
const int* p = &age;
p = &price;
Copy the code

Pointer to a const

Above we introduced Pointers to const, but there is another kind of pointer called const. A const pointer means that the pointer itself is const, and we can’t change the position it points to.

int age = 23;
int* const p = &age;
Copy the code

But it is ok to change the value to which the pointer points:

*p = 2333;	/ / legal
Copy the code

Both Pointers and contents are immutable

We can also superimpose both const s, making the object to which the pointer points and its value immutable:

const int * const p = &age;
Copy the code