Initializing structures and arrays of structures

suggest change

Structures and arrays of structures can be initialized by a series of values enclosed in braces, one value per member of the structure.

struct Date
{
    int year;
    int month;
    int day;
};

struct Date us_independence_day = { 1776, 7, 4 };

struct Date uk_battles[] =
{
    { 1066, 10, 14 },    // Battle of Hastings
    { 1815,  6, 18 },    // Battle of Waterloo
    { 1805, 10, 21 },    // Battle of Trafalgar
};

Note that the array initialization could be written without the interior braces, and in times past (before 1990, say) often would have been written without them:

struct Date uk_battles[] =
{
    1066, 10, 14,    // Battle of Hastings
    1815,  6, 18,    // Battle of Waterloo
    1805, 10, 21,    // Battle of Trafalgar
};

Although this works, it is not good modern style — you should not attempt to use this notation in new code and should fix the compiler warnings it usually yields.

See also designated initializers.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents