c - C中静态变量的初始化

标签 c static struct initialization

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

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

但是下面的数据结构呢:

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

static Hello hello[3];

hello[0], hello[1], hello[2] 中的所有成员都初始化为 0?

最佳答案

是的,所有成员都为具有静态存储的对象初始化。参见 C99 Standard (PDF document) 中的 6.7.8/10

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.

要将对象中的所有内容(无论是否为 static)初始化为 0,我喜欢使用通用零初始化程序

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

C 中没有部分初始化。一个对象要么被完全初始化(在没有不同值的情况下为正确类型的 0),要么没有被初始化全部。
如果您想要部分初始化,则不能从一开始就进行初始化。

int a[2]; // uninitialized
int b[2] = {42}; // b[0] == 42; b[1] == 0;
a[0] = -1; // reading a[1] invokes UB

关于c - C中静态变量的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13251083/

相关文章:

c++ - 如何在 C++ 中通过套接字从客户端向服务器发送结构体列表(序列化问题)?

c - 在C中使用数学库显示1弧度的正弦四舍五入到小数点后三位

c - 长度为零的 recv() 有效吗?

c - grep : (standard input): Bad file descriptor

c++ - 如何使用 c/c++ 宏参数创建字符串

c++ - 我可以使用 static 关键字只分配一次新内存吗?

无法在头文件中分配结构变量

c++ - 如何在 C++ 中创建指向 vector 的静态指针?

c# - 静态变量如何在网络场中工作?

c++ - 结构是 "reset"