C和C++中静态变量初始化的区别 [英] Difference between initialization of static variables in C and C++

查看:27
本文介绍了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++ 无论如何都需要支持动态初始化,否则你不能拥有带有非平凡构造函数的本地静态或非本地对象.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆