C++ global variable initialization order

痴心易碎 提交于 2019-12-02 17:55:41

The issue is a little bit subtle; please refer to C++11 3.6.2 for details.

What matters for us is that there are two phases of initialization of "non-local variables with static storage duration" (or "global variables" in colloquial parlance): the static initialization phase and the dynamic initialization phase. The static phase comes first. It looks like this:

int a = 0;
int x = 22;

The dynamic initialization runs afterwards:

a = f();

The point is that static initialization doesn't "run" at all - it only consists of setting values that are known at compile time, so those values are already set before any execution happens. What makes the initialization int x = 22; static is that the initializer is a constant expression.


There are cases where dynamic initialization may be hoisted to the static phase (but does not have to), but this is not one of those cases, because it does not meet the requirement that

the dynamic version of the initialization does not change the value of any other object of namespace scope prior to its initialization

When this hoisting happens, it is permissible that the resulting initial values can be different from if it didn't happen. There's an example in the standard for one such "indeterminate" initialization.

Also, consider:

#include <iostream>
using namespace std;

int f();
int g();

int a = f();
int b = g();

int main() {
        cout << a << " " << b;
}

int f() {
        b++;
        cout << "f" << endl;
        return 1;
}

int g() {
        cout << "g" << endl;
        return 2;
}

The output is:

f
g
1 2

Replacing b = g(); with b = 22; causes 1 23 to be printed. Kerrek SB's answer explains why this is.

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