Who`s Afraid to Be Const Correct? Reading Const Correctly in C++ - The Constant Value vs. La Valeur Constante
(Page 3 of 6 )
First I want to get rid of the confusion a const declaration can create. This confusion simply arises because of the two different types of programming styles the C++ standard allows: const int PI=3.14159265 has the same meaning as int const PI=3.14159265. Although it is much less common, I do prefer to use int const rather than const int to specify a “constant integer.” (Note that the French put the adjective after the noun instead of the other way around; so I can imagine that they wouldn’t find it strange to use ‘int const’ at all!)
Let me explain why I prefer it this way…
Personally, I prefer a consistent way to answer the question “What is constant?” Apparently there are two ways to answer this question (‘int const’ and ‘const int’): “either what comes after or before the const qualifier is const”… ouch! Not very helpful!
But with pointers (and references) it becomes a bit more complicated. When we apply const to a pointer there are two things we can constrain: the data pointed at (the user can’t make any modification to the data using the pointer) and/or the pointer itself (the user can’t change the address inside the pointer variable).
// a non-const pointer with non-const data
char *str = “you can modify this text”;
// a non-const pointer with const data
const char *str = “this looks very familiar”;
// another non-const pointer with const data
char const *str = “though this has my preference”;
// a const pointer with non-const data
char * const str = “you cannot modify the pointer”;
// a const pointer with const data
const char * const str = “cannot change anything”;
// another const pointer with const data
char const * const str = “and neither can this be changed”;
You see that it is impossible to apply the rule “const refers to what follows it” when we apply const to a pointer or reference. Take for example ‘char * value’. If we apply the rule when we try to make the pointer constant, it would become ‘char const * value’. Unfortunately this doesn’t make the pointer constant, but the data pointed at! Yes I agree: this is very confusing.
However the rule “const refers to what is in front of it” works when we apply it to a pointer or reference. The same example ‘char * value’ becomes ‘char * const value’. If we would like to make both the pointer and the data pointed at constant we would declare ‘char const * const value’.
Consistency pays off and I stick to this rule. Do you want to know which element is const? Just look at what is preceding the const keyword.
When you are reading other people’s code you should of course still understand what ‘const char * const’ implies.
Next: Syntactical Substitution Problems >>
More C++ Articles
More By J. Nakamura