What is a designated initializer in C?

2020-02-01 04:09发布

问题:

I know this might be a basic question.

I have an assignment that requires me to understand what 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?

回答1:

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