Reputation: 2589
I had this code:
int foo(void){
return 1;
}
int main(void){
static const int x = foo();
//do stuff
return 0;
}
But I got an error about initializing a static variable with a non-const value. I thought it had something to do with the const specifier, but it didn't. I ended dropping the const keyword and doing this:
int foo(void){
return 1;
}
int main(void){
static int x = 0;
if (x == 0) x = foo();
//do stuff
return 0;
}
Now, why can't the compiler just delay the initialization of the static int x
variable until it's used, and more importantly, why can't it just put it in a read-write section, and just enforce that it's not written to in compile time? I'd like to use the const
AND static
keyword for improved semantics in my code, but I don't really care how the compiler handles this, just let it work.
Is my understanding of the C standard wrong? Or is my compiler sucking? It's MSVC 9.0.
Upvotes: 7
Views: 3449
Reputation: 727087
This constraint comes from C standard's section 6.7.8/4, so it's not just your compiler:
All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.
The reason for this is that unlike C++ standard, C sdoes not require execution environments to provide an entry point for pre-run initialization (while certainly not prohibiting it; The manner and timing of static initialization (5.1.2) is unspecified).
Upvotes: 1
Reputation: 78993
The value for initialization must be determined at compile or link time. C doesn't have the concept of constructors that could be run at the startup of the program.
Upvotes: 1
Reputation: 145919
C requires it.
From the C Standard:
(C99, 6.7.8p4) "All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals."
Note that the const
qualifier does not mean constant but rather read-only. A const
object is not a constant in C.
The reason a static object cannot be initialized by a non constant value is related to the fact that the initialization of a static object is done "prior to program startup" (C99, 6.2.4p3).
Upvotes: 9