|
|
In hindsight, readonly would have been a better choice for a keyword than const. If one reads const in this manner, declarations such as:
char strcpy(char , const char );are easily understood to mean that the second parameter will only be used to read character values, while the first parameter will undoubtedly overwrite the characters to which it points. Furthermore, despite the fact that in the above example the type of
cpi
is a pointer to a
const int,
you can still change the value of the object to which it points
through some other means
(unless it actually points to an object declared with
const int type).
The two main uses for const are to declare (large) compile-time initialized tables of information as unchanging, and to specify that pointer parameters will not modify the objects to which they point.
The first use potentially allows portions of the data for a program to be shared by other concurrent invocations of the same program (just as the code for the program can be), and may cause attempts to modify this presumably invariant data to be detected immediately by means of some sort of memory protection fault, as the data resides in a read-only portion of memory.
The second use will most likely help locate potential errors (before generating a memory fault during that critical demo). For example, functions that temporarily place a null character into the middle of a string will be detected at compile time if passed a pointer to a string that cannot be so modified.