什么是 C 中的指定初始值设定项? [英] What is a designated initializer in C?
问题描述
我知道这可能是一个基本问题.
I know this might be a basic question.
我有一项任务要求我了解 C 中的指定初始值设定项是什么以及用 1 来初始化变量意味着什么.
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.
什么是 C 中的指定初始值设定项?
推荐答案
指定的初始化器有两种风格:
Designated initialisers come in two flavours:
1) 它提供了一种初始化数组中特定元素的快速方法:
1) It provides a quick way of initialising specific elements in an array:
int foo[10] = { [3] = 1, [5] = 2 };
会将所有元素设置为 foo
为 0,除了索引 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) 它提供了一种显式初始化 struct
成员的方法.例如,对于
2) It provides a way of explicitly initialising struct
members. For example, for
struct Foo { int a, b; };
你可以写
struct Foo foo { .a = 1, .b = 2 };
请注意,在这种情况下,未明确初始化的成员将被初始化,就像实例具有 static
持续时间一样.
Note that in this case, members that are not explicitly initialised are initialised as if the instance had static
duration.
<小时>两者都是标准 C,但请注意,C++ 不支持任何一个(因为构造函数可以使用该语言完成这项工作.)
Both are standard C, but note that C++ does not support either (as constructors can do the job in that language.)
这篇关于什么是 C 中的指定初始值设定项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!