In a project, I need to define a const int, I define it in a header as:
extern const int a;
And I include that header many times. Then in only one source file, I put:
const int a=10;
However when I need to use a in an array bound; i.e.:
int anarray[a];
I get:
"array bound is not an integer constant"
error. Why?
An array bound has to be an integral constant-expression. To be an integral constant-expression an expression must only involve (amongst a few other things) literals,
enumvalues andconstvariables orstaticdata members only if they are initialized with constant-expressions.constvariables of integer type are not integral constant-expressions if they don’t have a initializer.It’s a language rule that allows implementation to know certain constant values at compile time without having to know about other translation units (which may not be compiled at the same time and which may be changed independently).
constvariables at namespace scope have internal linkage by default (i.e. without an explicitextern) so you won’t have any multiple definition problems if you do something like this..