[ACCEPTED]-Are the members of a global structure initialized to zero by default in C?-initialization

Accepted answer
Score: 40

From the C99 standard 6.7.8/10 "Initialization":

If 27 an object that has automatic storage duration 26 is not initialized explicitly, its value 25 is indeterminate. If an object that has static 24 storage duration is not initialized explicitly, then:

— if 23 it has pointer type, it is initialized 22 to a null pointer;
— if it has arithmetic 21 type, it is initialized to (positive or 20 unsigned) zero;
— if it is an aggregate, every member 19 is initialized (recursively) according 18 to these rules;
— if it is a union, the 17 first named member is initialized (recursively) according 16 to these rules

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

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

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

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

Score: 8

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 2 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 1 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;
}
Score: 1

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

Score: 0

Yes, all global data is zeroed out, including 1 the members of structures, classes and unions.

More Related questions