What is a designated initializer in C?

喜夏-厌秋 提交于 2019-11-27 06:04:26

问题


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

来源:https://stackoverflow.com/questions/47202557/what-is-a-designated-initializer-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!