What is a designated initializer in C?

I have an assignment that requires me to understand what are designated initializers in C, and what it means to initialize a variable with one.

I am not familiar with the term and couldn't find any conclusive definitions.

What is a designated initializer in C?


  • Designated initialisers come in two flavours:

    1) It provides a quick way of initialising specific elements in an array:

    int foo[10] = { [3] = 1, [5] = 2 };

    will set all elements to foo to 0, other than index 3 which will be set to 1 and index 5 which will be set to 2.

    2) It provides a way of explicitly initialising struct members. For example, for

    struct Foo { int a, b; };

    you can write

    struct Foo foo { .a = 1, .b = 2 };

    Note that in this case, members that are not explicitly initialised are initialised as if the instance had static duration.

    Both are standard C, but note that C++ does not support either (as constructors can do the job in that language.)