C中静态变量的初始化 [英] The initialization of static variables in 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];
是hello[0]
、hello[1]
、hello[2]
的每个结构体中的所有成员初始化为<代码>0?
are all of the members in each struct of hello[0]
, hello[1]
, hello[2]
initialized as 0
?
推荐答案
是的,所有成员都针对具有静态存储的对象进行了初始化.参见 C99 标准(PDF 文档)中的 6.7.8/10)
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.
要将对象中的所有内容(无论是否为 static
)初始化为 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 中没有部分初始化.一个对象要么完全初始化(在没有不同值的情况下为正确类型的0
),要么没有在全部.
如果要部分初始化,就不能初始化.
There is no partial initialization in C. An object either is fully initialized (to 0
of the right kind in the absence of a different value) or not initialized at all.
If you want partial initialization, you can't initialize to begin with.
int a[2]; // uninitialized
int b[2] = {42}; // b[0] == 42; b[1] == 0;
a[0] = -1; // reading a[1] invokes UB
这篇关于C中静态变量的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!