Pointers in C: The Keyword const and Pointers

You have seen how a variable or an array can be declared as const to 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 charPtr is set pointing to the variable c. If the pointer variable is always set pointing to c, it can be declared as a const pointer as follows:

char * const charPtr = &c;

(Read this as “charPtr is 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 charPtr will not change through the pointer variable charPtr, that can be noted with a declaration as follows:

const char *charPtr = &c;

(Read this as “charPtr points to a constant character.”) Now of course, that doesn’t mean that the value cannot be changed by the variable c, which is what charPtr is 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 const says 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.

Source: Kochan Stephen G. (2004), Programming in C: A Complete Introduction to the C Programming Language, Sams; Subsequent edition.

Leave a Reply

Your email address will not be published. Required fields are marked *