Expert C Programming

(Jeff_L) #1

A const can be used for data, like so:


const int limit = 10;


and it acts somewhat as in other languages. When you add pointers into the equation, things
get a little rough:


const int * limitp = &limit;


int i=27;


limitp = &i;


This says that limitp is a pointer to a constant integer. The pointer cannot be used to


change the integer; however, the pointer itself can be given a different value at any time. It
will then point to a different location and dereferencing it will yield a different value!


The combination of const and * is usually only used to simulate call-by-value for array


parameters. It says, "I am giving you a pointer to this thing, but you may not change it."


This idiom is similar to the most frequent use of void *. Although that could


theoretically be used in any number of circumstances, it's usually restricted to converting
pointers from one type to another.


Analogously, you can take the address of a constant variable, and, well, perhaps I had better


not put ideas into people's heads. As Ken Thompson pointed out, "The const keyword


only confuses library interfaces with the hope of catching some rare errors." In retrospect,


the const keyword would have been better named readonly.


True, this whole area in the standard appears to have been rendered into English from Urdu via Danish
by translators who had only a passing familiarity with any of these tongues, but the standards
committee was having such a good time that it seemed a pity to ruin their fun by asking for some
simpler, clearer rules.


We felt that a lot of people would have questions in the future, and not all of them would want to
follow the process of reasoning shown above. So we changed the Sun ANSI C compiler to print out
more information about what it found incompatible. The full message now says:


Line 6: warning: argument #1 is incompatible with prototype:


prototype: pointer to pointer to const char : "barf.c", line


1


argument : pointer to pointer to char


Even if a programmer doesn't understand why, he or she will now know what is incompatible.


How Quiet is a "Quiet Change"?


Not all the changes in the standard stick out as much as prototypes. ANSI C made a number of other
changes, usually aimed at making the language more reliable. For instance, the "usual arithmetic

Free download pdf