The initialization of static variables in C

2019-01-05 04:23发布

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];

are all of the members in each struct of hello[0], hello[1], hello[2] initialized as 0?

4条回答
小情绪 Triste *
2楼-- · 2019-01-05 04:36

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.

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};
查看更多
【Aperson】
3楼-- · 2019-01-05 04:40

Yes, file-scope static variables are initialized to zero, including all members of structures, arrays, etc.

See this question for reference (I'll vote to close this as a duplicate, too).


Edit: this question is getting much better answers, so I'm voting to close that question as a duplicate of this, instead.

For reference, here is the C FAQ link from that question's accepted answer, although of course the C99 and C11 standards linked here are canonical.

查看更多
神经病院院长
4楼-- · 2019-01-05 04:57

I would add that static variables (or arrays) are classified into two types.

Initialized are the ones that are given value from code at compile time. These are usually stored in DS though this is compiler specific.

The other type is uninitialized statics which are initialized at run time and are stored into BSS segment though again this is compiler specific.

BSS

查看更多
趁早两清
5楼-- · 2019-01-05 05:00

Yes, they are, as long they have static or thread storage duration.

C11 (n1570), § 6.7.9 Initialization #10

If an object that has static or thread storage duration is not initialized explicitly, then:

[...]

  • 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, and any padding is initialized to zero bits;

[...]

查看更多
登录 后发表回答