Pointers and const
Using const
with pointers has some subtle aspects (pointers always seem to have subtle aspects), so let’s take a closer look. You can use the const
keyword two different ways with pointers. The first way is to make a pointer point to a constant object, and that prevents you from using the pointer to change the pointed-to value. The second way is to make the pointer itself constant, and that prevents you from changing where the pointer points. Now for the details.
First, let’s declare a pointer pt
that points to a constant:
int age = 39;const int * pt = &age;
This declaration states that pt
points to a const int
(39
, in this case). Therefore, you can’t use pt
to change that value. In other words, the value *pt
is const
and cannot ...
Get C++ Primer Plus now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.