Wednesday, January 30, 2008

The differences of 'const' in C/C++

This confused me a little bit in former experience. Look at the description from ThinkinginC++ book:

In C, a const always occupies storage and its name is global. The C compiler cannot treat a const as a compile-time constant. In C, if you say

const int bufsize = 100;
char buf[bufsize];

you will get an error. Because bufsize occupies storage somewhere, the C compiler cannot know the value at compile time. You can optionally say

const int bufsize;

in C, but not in C++, and the C compiler accepts it as a declaration indicating there is storage allocated elsewhere. Because C defaults to external linkage for consts. C++ defaults to internal linkage for consts so if you want to accomplish the same thing in C++, you must explicitly change the linkage to external using extern

extern const int bufsize; // Declaration only

No comments:

Post a Comment