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++ 编译器中可以很好地编译。
我的问题是,当 static 在两种语言中具有相同的用法时,为什么它会在 C++ 编译器中编译。当然,这些语言的编译器会有所不同,但我无法指出确切的原因。如果标准中有规定,我很想知道。
我在 SO 上搜索了这个问题,发现了这些类似的问题:
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;
}
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.
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.
I searched for this question on SO , found these similar questions:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它在 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.
So since C++ has this complexity anyway, supporting that initialization like you show isn't complicated to add anymore.
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.
6.7.8/4 [C99]
在
static int i =initializer();
中,RHS 不是常量表达式,因此代码无法在 C 中编译。在 C++ 中没有这样的限制,并且代码在 C++ 中格式良好。
6.7.8/4 [C99]
In
static int i = initializer();
the RHS is not a constant expression and so the code doesn't compile in C.In C++ there is no such restriction and the code is well-formed in C++.
C 中的静态变量需要使用编译时已知的值进行初始化。此要求已在 C++ 中删除,您可以使用在运行时计算的表达式来初始化它们。
这两种语言在这一点以及许多其他方面都有所不同。您可以很容易地编写 C++ 编译器可以接受的 C 代码,但反之则不然。
Static variables in C need to be initialised with a value known at compile time. This requirement has been removed in C++, and you can initialise them with expressions evaluated at run-time.
The two languages differ in this, and many, many other respects. You can quite easily write C code which will be acceptable to a C++ compiler, but the reverse is not true.