const pointer
To make the pointer itself a
const, you must place the const specifier to the right of the
*, like this:
int d = 1;
int* const w = &d;
Now it reads: “w is a
pointer, which is const, that points to an int.” Because the
pointer itself is now the const, the compiler requires that it be given
an initial value that will be unchanged for the life of that pointer. It’s
OK, however, to change what that value points to by saying
*w = 2;
You can also make a const pointer
to a const object using either of two legal forms:
int d = 1;
const int* const x = &d; // (1)
int const* const x2 = &d; // (2)
Now neither the pointer nor the object
can be changed.
Some people argue that the second form is
more consistent because the const is always placed to the right of what
it modifies. You’ll have to decide which is clearer for your particular
coding style.
Here are the above lines in a compileable
file:
//: C08:ConstPointers.cpp
const int* u;
int const* v;
int d = 1;
int* const w = &d;
const int* const x = &d; // (1)
int const* const x2 = &d; // (2)
int main() {} ///:~