Who`s Afraid to Be Const Correct? Reading Const Correctly in C++ - Syntactical Substitution Problems
(Page 4 of 6 )
Another reason to put const after that which you would like to apply it to, is that things become very muddy when you apply const to syntactical substitutions. Assume the following typedef:
typedef int* INTPTR;
You saw that ‘const int’ and ‘int const’ have the same meaning: the int value is constant. But how does the compiler interpret ‘const CHARPTR’ or ‘CHARPTR const’? Have a look at the following test example:
// test.cpp
#include <stdio.h>
typedef int* INTPTR;
void foo1(const INTPTR val) { *val = 42; }
void foo2(/*const*/ int* val) { *val = 42; }
void bar1(INTPTR const val) { *val = 42; }
void bar2(int * const val) { *val = 42; }
int main()
{
int value = 0;
foo1(&value);
(void)printf(“value is %d\n”, value);
value = 0;
foo2(&value);
(void)printf(“value is %d\n”, value);
value = 0;
bar1(&value);
(void)printf(“value is %d\n”, value);
value = 0;
bar2(&value);
(void)printf(“value is %d\n”, value);
return 0;
}
Were you surprised that the compiler didn’t complain and that ‘value’ was assigned ‘42’ every time? If you expected ‘const INTPTR’ to be interpreted as ‘const int *’, you were definitely in for a surprise, because somehow you were allowed to change the data pointed at to 42 when value was declared as ‘const INTPTR’ but not when it was ‘const int *’!
Apparently ‘const INTPTR’ does not translate to ‘const int *’… what is going on?
Lets consider ‘const int i;’ for a moment again. We saw that there is no difference between ‘const int i;’ and ‘int const i;’. Both statements declare ‘i’ as being constant. The same thing happens with the typedef. The compiler interprets ‘const INTPTR i;’ as if it was declared ‘INTPTR const i;’ and the last statement expands to ‘int * const i;’ declaring the pointer constant -- and not the data pointed at!
Next: Const Member Functions >>
More C++ Articles
More By J. Nakamura