用C静态变量的初始化 [英] The initialization of static variables in C

查看:132
本文介绍了用C静态变量的初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态变量在C初始化我知道的问题,如果我们声明一个全局静态变量的默认值是 0 。例如:

I have a question about the initialization of static variables in C. I know if we declare a global static variable that by default the value is 0. For example:

static int a; //although we do not initialize it, the value of a is 0

但什么数据结构如下:

but what about the following data structure:

typedef struct
{
    int a;
    int b;
    int c;
} Hello;

static Hello hello[3];

是所有成员在你好[0] 你好[1] ,<$每个结构C $ C>你好[2] 初始化为 0

推荐答案

是的,所有成员都与静态存储对象初始化。见6.7.8 / 10在 C99标准(PDF文件)

Yes, all members are initialized for objects with static storage. See 6.7.8/10 in the C99 Standard (PDF document)

如果具有自动存储时间的对象没有明确初始化,它的价值是不确定的。 如果有静态存储持续时间的对象没有初始化明确,然后:结果
   - 如果它有指针的类型,它被初始化为空指针;结果
   - 如果有算术类型,它被初始化为(正或无符号的)为零;结果,
   - 如果它是集料,每件被初始化(递归地)根据这些规则;结果
   - 如果它是一个联盟,首批命名部件(递归)根据这些初始化
  规则。

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules;
— if it is a union, the first named member is initialized (recursively) according to these rules.

要在对象初始化的一切,无论是静态或不为0的,我喜欢使用的通用零初始

To initialize everything in an object, whether it's static or not, to 0, I like to use the universal zero initializer

sometype identifier0 = {0};
someothertype identifier1[SOMESIZE] = {0};
anytype identifier2[SIZE1][SIZE2][SIZE3] = {0};

这篇关于用C静态变量的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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