What is a designated initializer in C?

user7349461 picture user7349461 · Nov 9, 2017 · Viewed 8.6k times · Source

I know this might be a basic question.

I have an assignment that requires me to understand what a Designated initializers in C are 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?

Answer

Bathsheba picture Bathsheba · Nov 9, 2017

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.)