Are the members of a global structure initialized to zero by default in C?
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.
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.