简体   繁体   中英

Are the members of a global structure initialized to zero by default in C?

C 中全局或静态结构的成员是否保证自动初始化为零,就像未初始化的全局或静态变量一样

From the C99 standard 6.7.8/10 "Initialization":

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

Since globals and static structures have static storage duration, the answer is yes - they are zero initialized (pointers in the structure will be set to the NULL pointer value, which is usually zero bits, but strictly speaking doesn't need to be).

The C++ 2003 standard has a similar requirement (3.6.2 "Initialization of non-local objects"):

Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place.

Sometime after that zero-initialization takes place, constructors are called (if the object has a constructor) under the somewhat more complicated rules that govern the timing and ordering of those calls.

Local variables are not initialized.

struct foobar {
    int x;
};

int main(void) {
    struct foobar qux;
    /* qux is uninitialized. It is a local variable */
    return 0;
}

static local variables are initialized to 0 (zero)

struct foobar {
    int x;
};

int main(void) {
    static struct foobar qux;
    /* qux is initialized (to 0). It is a static local variable */
    return 0;
}

Global variables are initialized to 0 (zero)

struct foobar {
    int x;
};
struct foobar qux;
/* qux is initialized (to 0). It is a global variable */

int main(void) {
    return 0;
}

A struct is no different in this manner than a normal static C variable. The memory reserved for that struct is completely initialized to 0 if it's a static.

是的,所有全局数据都被清零,包括结构、类和联合的成员。

All data in global part of the program is set to zero.

The BSS segment also known as Uninitialized data starts at the end of the data segment and contains all uninitialized global variables and static variables that are initialized to zero by default. For instance a variable declared static int i; would be contained in the BSS segment.

Bss segment .

I don't know why is it so hard to try it yourself btw.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM