Professional Documents
Culture Documents
PROGRAMMING POINTERS
Dan Saks
By changing the value of x[0], the means. A program can use the pointer of one type into a pointer of a
program also changes the value of *p. expression p to alter the value of the compatible type that uses the const
The expression p has an unquali- pointer object that p designates, but it qualifier differently. Such a conver-
fied type. Therefore, the program can can’t use the expression *p to alter sion is a qualification conversion.
change the value of the object that p the value of any objects that *p might However, both languages restrict
designates. After: designate. If the program has another qualification conversions in a way that
expression e of unqualified type that allows for a consistent notion of
++p; designates an object that *p also des- objects that are truly read-only and
ignates, the program can still use e to can reside in ROM.
*p designates the same object as x[1]. change that object. Let’s look at a slight variation on
The program still can’t use *p to Thus, a program might be able to the previous example:
change the object, but now changing change an object right out from
the value of x[1] effectively changes under a const-qualified expression. int n = 0;
the value of *p. If that’s so, then what good is the int const *p = &n; // ok
Thus, a program can alter the const qualifier? Does it really do any-
value of *p after all. It just can’t use *p thing? Fortunately, it does. Even Here, n designates a modifiable int
to do it. Rather, it must use an though the const qualifier doesn’t object. At this point, the compiler
unqualified expression such as x[i]. have as much oomph as you might knows that code later in the program
Here, then, is a more precise state- have expected, it still has enough so is allowed to alter that int object.
ment of what a declaration such as: that you can do some useful things Therefore, it cannot place the object
with it. in ROM.
T const *p; C and C++ programs can convert a The expression &n has type “point-
er to int.” The declaration for p con-
verts &n to type “pointer to constint,”
adding a const qualifier in the
process. This is a valid qualification
conversion. This conversion in no way
invalidates n’s declaration. The pro-
gram can still use n to alter the int
object, even if it can’t use *p for the
same purpose.
In contrast, consider: