15.1 const Pointers
Declaring
constant pointers is a little tricky. For example, although the
declaration:
const int result = 5;
tells C++ that result is a constant, so:
result = 10; // Illegal
is illegal. The declaration:
const char *answer_ptr = "Forty-Two";
does not tell C++ that the variable
answer_ptr is a constant. Instead it tells C++
that the data pointed to by answer_ptr is a
constant. The data cannot be changed, but the pointer can. Again we
need to make sure we know the difference between
"things" and
"pointers to things."
What's answer_ptr? A pointer. Can
it be changed? Yes, it's just a pointer. What does
it point to? A const char array. Can the data
pointed to by answer_ptr be changed? No,
it's constant.
Translating these rules into C++ syntax we get the following:
answer_ptr = "Fifty-One"; // Legal (answer_ptr is a variable)
*answer_ptr = 'X'; // Illegal (*answer_ptr is a constant)
If you put the const after the
*, you tell C++ that the pointer is constant. For
example:
char *const name_ptr = "Test";
What's name_ptr? A constant
pointer. Can it be changed? No. What does it point to? A character.
Can the data we pointed to by name_ptr be changed?
Yes.
name_ptr = "New"; // Illegal (name_ptr is constant)
*name_ptr = 'B'; // Legal (*name_ptr is a char)
Finally, we put const in both places, creating a
pointer that cannot be changed to a data item that cannot be changed:
const char *const title_ptr = "Title";
One way of remembering whether the const modifies
the pointer or the value is to remember that
*const reads "constant
pointer" in English.
|