Initializers provide an initial value for objects, and follow this syntax:
expression
{ initializer-list }
{ initializer-list, }
initializer initializer-list, initializer
Initialization of objects of each type is discussed in the following sections, but a few universal constraints apply to all initializations in C:
struct t1 {
int i;
double d;
};
union t2 {
int i;
double d;
};
struct t3 {
struct t1 s;
union t2 u;
};
struct t3 st[] = { /* complete initializer */
1, 2, 0, 4, 0, 0, 7, 0, 0
};
Given the previous declarations, the variable st is
an array of 3 structures. Its initial contents are:
s u
------ -
st[0]: 1, 2.0, 0
st[1]: 4, 0.0, 0
st[2]: 7, 0.0, 0
This variable can also be defined in the following ways-all four initializers are equivalent:
struct t3 st[] = { /* partial initializer */
1, 2, 0, 4, 0, 0, 7
};
struct t3 st[] = { /* nested and complete initializers */
{1, 2, 0},
{4, 0, 0},
{7, 0, 0}
};
struct t3 st[] = { /* nested and partial initializers */
{1, 2},
{4},
{7}
};
C has historically allowed initializers to be optionally surrounded by extra braces (to improve formatting clarity, for instance). These initializers are parsed differently depending on the type of parser used. DEC C uses the parsing technique specified by the ANSI standard, known as the top-down parse. Programs depending on a bottom-up parse of partially braced initializers can yield unexpected results. The compiler generates a warning message when it encounters unnecessary braces in common C compatibility mode or when the error-checking compiler option is specified on the command line.