用C中的变量初始化全局变量 [英] Initializing globals with variables in C

查看:169
本文介绍了用C中的变量初始化全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的#include指令之后,在文件顶部定义了以下变量;

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.

推荐答案

正如您所说,全局变量隐式具有静态存储持续时间.这是因为全局变量是在编译时初始化的.因此,这正是您遇到错误的原因.

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.

来自 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.
}

这篇关于用C中的变量初始化全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆