struct-type initialization
Template:c/language/initialization/navbar
This is the initialization performed when a structure is constructed.
[edit] Explanation
If a structure has automatic storage duration and is not initialized explicitly, its initial values are indeterminate.
If a structure has static or thread storage duration and is not initialized explicitly and a member of the structure has
- pointer type, the member is initialized to a null pointer;
- arithmetic type, the member is initialized to (positive or unsigned) zero;
- aggregate type, the member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
- union type, the member is initialized such that the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits.
The initializer for a structure object that has automatic storage duration shall be either an initializer list or a single expression that has compatible structure type.
When no designator is present, initialization of structure members occurs in declaration order. Designators can change the order of the initialization of structure members.
If a structure contains elements or members that are arrays, structures, or unions, these rules apply recursively to the sub-arrays, sub-structures, or contained unions.
If a structure is initialized, members that are not initialized explicitly are initialized implicitly the same as elements that have static storage duration.
The evaluations of the initialization list expressions are indeterminately sequenced with respect to one another and thus the order in which any side effects occur is unspecified.
[edit] Example
int main(void) { struct S1 { char c; int i; } s1; /* initial values are indeterminate */ static struct S2 { char c; int i; } s2; /* static storage duration: '',0 */ struct S3 { char c; int i; } s3 = {'a',1}; /* declaration order */ struct S4 { char c; int i; } s4 = {.i=1,.c='a'}; /* designators change initialization order */ struct S5 { char c; int i; } s5 = {'a'}; /* too few initializers: 'a',0 */ struct S6 { /* sub-array */ char c; int i[5]; } s6 = { 'a',{1,2,3,4,5} }; struct S7 { /* sub-structure */ struct s { char c; int i; } ss; char c; } s7 = { {'a',1}, 'b' }; struct S8 { /* sub-union */ union u { short int si; int i; long int li; } uu; char c; } s8 = { {1}, 'b' }; return 0; }
Possible output:
(none)