问题
I having the following variables defined at the top of my file right after my #include
directives;
int a = 5;
int b = a;
But I get a compile time error. I know that global variables implicitly have static storage duration, but I'm not sure how or if this is related to the cause of this error.
回答1:
As you said, global variables implicitly have static storage duration. This is because global variables are initialised during compile time. So this is precisely the reason why you are getting an error.
From C99 Standard 6.7.8:
All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.
To get past this rule, you could use the following "trick".
int a = 5;
int b;
int main()
{
b = a;
//rest of code goes here.
}
来源:https://stackoverflow.com/questions/42287786/initializing-globals-with-variables-in-c