If you have a variable (or function argument - it doesn't matter) declared as const char *a, that makes
a=NULL; // legal *a = 'a'; // not legal
However, if it's declared as char * const a, then
a=NULL; // not legal *a = 'a'; // legal
Quotes from Bob Elman (The C Guru!):
Last updated on 2005-06-21 14:00:00 -0800, by Shalom Craimer
- "If you declare something like const char *a, that's saying that the thing pointed to by a is a const, but a itself is not. It's perfectly legal to assign a different pointer value to a. You just can't store THROUGH a into the target."
- "char * const a; - That's a perfectly legal declaration. With that one, you can't change where a points, but you can change the memory pointed to, i.e., the target."
- "When reading a declaration, always start from the variable name and read outwards. Thus char * const a; is read as: A is a constant pointer to a character."
- "When they were designing the C language, they tried an experiment that to my knowlege had never been tried before. They made declarations look like references. In earlier languages, declarations and references used very different syntax. The reason is that nobody had come up with a usage syntax that could be read as a declaration."
- "If you wanted a pointer to a constant array, you would write char const *a - (Reading from the variable outwards): A is a pointer to a constant character. In fact, the language spec DOES say that this is how you should write the declaration.
- However, you put storage class words like "static", "auto", "register", "extern" and "typedef" in front of the declaration and people had too hard a time keeping track of the distinction between a "storage class modifier" and a "qualifier".
So, to make life easier, the spec was loosened a bit to make char const equivalent to const char and from that we get the current idiom of const char *a.- In const char const * a, the two const's are equivalent to one another and is technically a permitted redundancy.
Back to Tech Journal