什么时候初始化全局变量? [英] When does initialisation of global variables happen?

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

问题描述

我知道当程序运行时,首先执行 main() 函数.但是在 main() 之外声明的全局变量的初始化什么时候发生呢?我的意思是,如果我声明一个这样的变量:

unsigned long current_time = millis();无效主(){尽管 () {//一些使用current_time全局变量的代码}}

这里,全局变量初始化的确切时间很重要.请说出在这种情况下会发生什么.

解决方案

由于您没有定义您所谈论的语言,我假设它是 C++.

<块引用>

在计算机编程中,全局变量是在每个范围内都可以访问的变量(除非被隐藏).与全局变量的交互机制称为全局环境(另见全局状态)机制.全局环境范式与局部环境范式形成对比,其中所有变量都是本地的,没有共享内存(因此所有交互都可以重新进行消息传递).维基百科.

<小时><块引用>

原则上,在调用main()之前,在任何函数之外定义的变量(即全局、命名空间和类静态变量)都会被初始化.翻译单元中的此类非局部变量按其声明顺序(第 10.4.9 节)进行初始化.如果这样的变量没有显式初始值设定项,则默认情况下将其初始化为其类型的默认值(第 10.4.2 节).内置类型和枚举的默认初始化值为 0. [...] 不同翻译单元中全局变量的初始化顺序没有保证.因此,在不同编译单元中的全局变量的初始值设定项之间创建顺序依赖是不明智的.此外,不可能捕获全局变量的初始化程序抛出的异常(第 14.7 节).通常最好尽量减少全局变量的使用,特别是限制需要复杂初始化的全局变量的使用..

I know when a program is run, the main() function is executed first. But when does the initialization of global variables declared outside the main() happens? I mean if I declare a variable like this:

unsigned long current_time = millis();

void main() {
    while () {
        //some code using the current_time global variable 
    }
}

Here, the exact time when the global variable initializes is important. Please tell what happens in this context.

解决方案

Since you didn't define the language you're talking about, I assumed it to be C++.

In computer programming, a global variable is a variable that is accessible in every scope (unless shadowed). Interaction mechanisms with global variables are called global environment (see also global state) mechanisms. The global environment paradigm is contrasted with the local environment paradigm, where all variables are local with no shared memory (and therefore all interactions can be reconducted to message passing). Wikipedia.


In principle, a variable defined outside any function (that is, global, namespace, and class static variables) is initialized before main() is invoked. Such nonlocal variables in a translation unit are initialized in their declaration order (§10.4.9). If such a variable has no explicit initializer, it is by default initialized to the default for its type (§10.4.2). The default initializer value for built-in types and enumerations is 0. [...] There is no guaranteed order of initialization of global variables in different translation units. Consequently, it is unwise to create order dependencies between initializers of global variables in different compilation units. In addition, it is not possible to catch an exception thrown by the initializer of a global variable (§14.7). It is generally best to minimize the use of global variables and in particular to limit the use of global variables requiring complicated initialization. See.

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

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