何时全局变量初始化发生的呢? [英] When does initialisation of global variables happen?

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

问题描述

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

 无符号长CURRENT_TIME =米利斯();无效的主要(){
    而(){
        //使用CURRENT_TIME全局变量一些code
    }
}

下面,当全局变量初始化的确切时间是很重要的。请告诉在这方面发生了什么。


解决方案

既然你没有定义你在说什么语言,我认为它是C ++。


  

在计算机编程中,全局变量是一个变量,在每个范围访问(除非阴影)。全局变量的相互作用机制被称为全球环境(见全局状态)的机制。全球环境范例是对比当地环境的范例,其中所有的变量是局部的,没有共享内存(并因此所有交互可以reconducted到消息传递)。 维基百科




  

在原则上,()任何函数之外定义一个变量(即,全局命名空间和类的静态变量)之前主初始化被调用。在翻译单元这样的非本地变量的声明顺序(§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天全站免登陆