woensdag 20 juni 2007

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 a constant, and that prevents you from changing where the pointer points.

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). Therefor, you can't use pt to change that value. In other words, the value *pt is const and cannot be modified:

*pt += 1; // INVALID because pt points to a const int
cin >> *pt; // INVALID for the same reason

Now for a subtle point. This declaration for pt doesn't necessarily mean that the value it points to is really a constant; it just means the value is a constant insofar as pt is concerned.
For example, pt points to age, and age is not const. You can change the value of age directly by using the age variable, but you can't change the value indirectly via the pt pointer:

*pt = 20; // INVALID because pt points to a const int
age = 20; // VALID because age is not declared to be const

In the past, you've assigned the address of a regular variable to a regular pointer. Now you've assigned the address of a regular variable to a pointer-to-const. That leaves two other possibilities: assigning the address of a const variable to a pointer-to-const and assigning the address of a const to a regular pointer. Are they both possible? The first is, and the second isn't:

const float g_earth = 9.80;
const float * pe = &g_earth; // VALID

const float g_moon = 1.63;
float * pm = &g_moon; // INVALID

For the first case, you can use neither g_earth nor pe to change the value 9.80. C++ doesn't allow the second case for a simple reason: If you assign the address of g_moon to pm, then you can cheat and use pm to alter the value of g_moon.
That makes a mockery of g_moon's const status, so C++ prohibits you from assigning the address of a const to a non-const pointer.
(if you are really desperate, you can use a type cast to override the restriction; see const_cast operator)

The situation becomes a bit more complex if you have pointers to pointers. As you saw earlier, assigning a non-const pointer to a const pointer is okay, provided that you're dealing with just one level of indirection:

int age = 39; // age++ is a valid operation
int * pd = &age; // *pd = 41 is a valid operation
const int * pt = pd; // *pt = 42 is an INVALID operation

But pointer assignments that mix const and non-const in this manner are NO longer SAFE when you go to two levels of indirection. If mixing const and non-const were allowed, you could do something like this:

const int **pp2;
int *p1;
const int n = 13;
pp2 = &p1; // not allowed, but suppose it were
*pp2 = &n; // valid, both const, but sets p1 to point at n
*p1 = 10; // valid, but changes const n

Suppose you have an array of const data:

const int months[12] = {31,28,31,30,31,,30,31,31,30,31,30,31};

The prohibition against assigning the address of a constant array means that you cannot pass the array name as an argument to a function by using a non-const formal argument:

int sum(int arr[], int n); // should have been const int arr[]
...
int j = sum(months, 12); // NOT allowed

This function call attempts to assign a const pointer (months) to a non-const pointer (arr), and the compiler disallows the function call.

Using const When You Can
There are two strong reasons to declare pointer arguments as pointers to constant data:
- It protects you against programming errors that inadvertently alter data
- Using const allows a function to process both const and non-const actual arguments, whereas a function that omits const in the prototype can accept
only non-const data.
You should declare formal pointer arguments as pointers to const whenever it's appropriate to do so.

For yet another subtle point, consider the following declarations:

int age = 39;
const int * pt = &age;

The const in the second declaration only prevents you from changing the value to which pt points, which is 39. It does not prevent you from changing the value of pt itself. That is, you can assign a new value to pt:

int sage = 80;
pt = &sage; // okay to point to another location'

But you still can't use pt to change the value to which it points(now 80)

The second way to use const makes it impossible to change the value of the pointer itself:

int sloth = 3;
const int * ps = &sloth; // a pointer to const int
int * const finger = &sloth; a const pointer to int

Note that the last declaration has repositioned the keyword const. This form of declaration constrains finger to point only to sloth. However, it allows you to use finger to alther the value of sloth. The middle declaration does not allow you to use ps to alter the value of sloth, but it permits you to have ps point to another location. In short, finger and *ps are both const, and *finger and ps are not const.

If you like, you can declare a const pointer to a const object:
double trouble = 2.0E30;
const double * const stick = &trouble;

Here stick can point only to trouble, and stick cannot be used to change the value of trouble. In short both stick and *stick are const.

Typically you use the pointer to const form to protect data when you pass pointers as function arguments. For example:

void show_array(const double ar[], int n);

Using const in this declaration means that show_array() cannot alter the values in any array that is passed to it. This technique works as long as there is just one level of indirection. Here for example, the array elements are fundamental type, but if they where pointers or pointers-to-pointers, you wouldn't use const.

Geen opmerkingen: