I cannot get the reason behind being unable to initialize static variables withOUT constant literals.
This initialization is perfectly fine, it compiles :
#include <stdio.h>
int main ()
{
static int i = 15;
}
While this one isn't, and doesn't compile :
#include <stdio.h>
int initializer ()
{
return 15;
}
int main ()
{
static int i = initializer();
}
And neither does this one compile :
#include <stdio.h>
int main ()
{
int x = 15;
static int i = x;
}
For the last 2 programs the compiler gives this error :
Initializer element is not constant.
When I researched the reason for this, I came up with two explanations; one from https://www.geeksforgeeks.org/g-fact-80/ and the other from C99 Standard 5.1.2 Execution Environments.
GeeksforGeeks states "All objects with static storage duration must be initialized (set to their initial values) before execution of main()
starts. So a value which is not known at translation time cannot be used for initialization of static variables."
C99 Standard states "All objects with static storage duration shall be initialized (set to their initial values) before program startup."
But what do these sentences really mean? And what do these have to do with constant literals? When I declare a static variable inside main()
function as the first code piece it compiles, and because the declaration is inside main()
the execution of main()
has already started. So the initialization takes place AFTER "the execution of main starts" , in contrast to GeeksforGeeks' statement.