C和C++中静态变量初始化的区别
我正在http://geeksforgeeks.org/?p=10302
#include<stdio.h>
int initializer(void)
{
return 50;
}
int main()
{
static int i = initializer();
printf(" value of i = %d", i);
getchar();
return 0;
}
此代码不会在 C 中编译,因为需要在 main() 启动之前初始化静态变量.没事儿.但是这段代码在 C++ 编译器中可以很好地编译.
This code will not compile in C because static variables need to be initialised before main() starts. That is fine. But this code will compile just fine in a C++ compiler.
我的问题是,当 static 在两种语言中的用法相同时,为什么它会在 C++ 编译器中编译.当然,这些语言的编译器会有所不同,但我无法指出确切原因.如果标准中有规定,我很想知道.
My question is why it compiles in a C++ compiler when static has the same usage in both languages. Of course compilers will be different for these languages but I am not able to pin point the exact reason. If it is specified in the standard, I would love to know that.
我在 SO 上搜索了这个问题,发现了这些类似的问题:
I searched for this question on SO , found these similar questions:
- C 中的静态和 C++ 中的静态之间的区别??
- 静态变量初始化顺序
- C 和 C++ 中的静态变量
推荐答案
它用 C++ 编译,因为 C++ 无论如何都需要支持动态初始化,否则你不能拥有带有非平凡构造函数的本地静态或非本地对象.
It compiles in C++ because C++ needs to support dynamic initialization anyway, or you couldn't have local static or non-local objects with non-trivial constructors.
因此,由于 C++ 无论如何都具有这种复杂性,因此支持像您展示的那样的初始化不再复杂.
So since C++ has this complexity anyway, supporting that initialization like you show isn't complicated to add anymore.
在 C 中这将是一个大问题,因为 C 没有任何其他理由支持在程序启动时完成的初始化(除了微不足道的 零初始化).在 C 中,文件范围或本地静态对象的初始值总是可以静态地放入可执行映像中.
In C that would be a big matter because C doesn't have any other reason to support initialization done at program startup (apart from trivial zero initialization). In C, initial values of file-scope or local static objects can always statically be put into the executable image.
相关文章