gpt4 book ai didi

c++ - 外部变量的初始化

转载 作者:太空狗 更新时间:2023-10-29 20:51:19 25 4
gpt4 key购买 nike

我有 3 个文件,如下所示:

//1.hpp
extern int a;
//1.cpp
#include "1.hpp"
int a = 44;
//2.cpp
#include <iostream>

using namespace std;

extern int a;
int main()
{
cout << endl << a;
return 0;
}

上面的程序给出了 44 作为输出。我想问一下是否可以保证输出始终为 44,因为对我来说这个程序工作的确切顺序并不明显,即说 'a' 的初始化在它用于主要函数?

最佳答案

是的,这保证a会在main()执行之前被初始化。对于 non-local variables with static storage duration ,

All non-local variables with static storage duration are initialized as part of program startup, before the execution of the main function begins (unless deferred, see below).

所有在命名空间范围内声明的对象(包括全局命名空间)都有static storage duration .

关于c++ - 外部变量的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50640921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com