在C和C静态变量的初始化区别++ [英] Difference between initialization of static variables in C and C++
问题描述
我在 http://geeksforgeeks.org/?p=10302 经历了code p>
I was going through the code at 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;
}
这code将不是在C编译,因为静态变量需要前主让被初始化()开始。没事儿。但是,这code将编译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.
我的问题是,为什么在编译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,发现3相似的链接,但徒劳无功。
<一href=\"http://stackoverflow.com/questions/943280/difference-between-static-in-c-and-static-in-c\">Link1
链路2
链接3
I searched for this question on SO , found 3 similar links but in vain. Link1 Link2 Link3
感谢您的帮助。
推荐答案
它编译的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.
这篇关于在C和C静态变量的初始化区别++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!