且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C和C++中静态变量初始化的区别

更新时间:2022-01-21 02:14:46

它用 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.