Initializing globals with variables in C

ぃ、小莉子 提交于 2019-12-12 01:22:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!