Programming in C

(Barry) #1
The Keyword constand Pointers 253

The Keyword constand Pointers


You have seen how a variable or an array can be declared as constto alert the compiler
as well as the reader that the contents of a variable or an array will not be changed by
the program.With pointers, there are two things to consider: whether the pointer will be
changed, and whether the value that the pointer points to will be changed.Think about
that for a second. Assume the following declarations:


char c = 'X';
char *charPtr = &c;


The pointer variable charPtris set pointing to the variable c. If the pointer variable is
always set pointing to c, it can be declared as a constpointer as follows:


char * const charPtr = &c;


(Read this as “charPtris a constant pointer to a character.”) So, a statement like this:


charPtr = &d; // not valid


causes the GNU C compiler to give a message like this:^2


foo.c:10: warning: assignment of read-only variable 'charPtr'


Now if, instead, the location pointed to by charPtrwill not change through the pointer
var iable charPtr, that can be noted with a declaration as follows:


const char *charPtr = &c;


(Read this as “charPtrpoints to a constant character.”) Now of course, that doesn’t
mean that the value cannot be changed by the variable c, which is what charPtris set
pointing to. It means, however, that it won’t be changed with a subsequent statement like
this:


*charPtr = 'Y'; // not valid


which causes the GNU C compiler to issue a message like this:


foo.c:11: warning: assignment of read-only location


In the case in which both the pointer variable and the location it points to will not be
changed through the pointer, the following declaration can be used:


const char const charPtr = &c;


The first use of constsays the contents of the location the pointer references will not be
changed.The second use says that the pointer itself will not be changed. Admittedly, this
looks a little confusing, but it’s worth noting at this point in the text.^3


2.Your compiler may give a different warning message, or no message at all.
3.The keyword constis not used in every program example where it can be employed; only in
selected examples. Until you are familiar with reading expressions such as previously shown, it can
make understanding the examples more difficult.

Free download pdf