指定初始化器有两种类型:
1)它提供了一种快速初始化数组中特定元素的方法:
int foo[10] = { [3] = 1, [5] = 2 };
除了索引为3的元素将被设置为1,索引为5的元素将被设置为2之外,它将所有元素foo
都设置为0。
2)它提供了一种显式初始化struct
成员的方法。例如,用于
struct Foo { int a, b; };
你可以编写代码
struct Foo foo { .a = 1, .b = 2 };
请注意,在这种情况下,没有显式初始化的成员将被初始化,就好像该实例具有静态持续时间。
标准初始化
int a[6] = { 0, 0, 15, 0, 29, 0 };
int a[6] = {[4] = 29, [2] = 15 }; // or
int a[6] = {[4]29 , [2]15 }; // or
int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 };
标准初始化
struct point { int x, y; };
struct point p = { .y = 2, .x = 3 }; or
struct point p = { y: 2, x: 3 };
int a[6] = { 0, v1, v2, 0, v4, 0 };
int a[6] = { [1] = v1, v2, [4] = v4 };
给数组初始化器的元素加上标签
int whitespace[256] = { [' '] = 1, ['\t'] = 1, ['\h'] = 1,
['\f'] = 1, ['\n'] = 1, ['\r'] = 1 };
struct point ptarray[10] = { [2].y = yv2, [2].x = xv2, [0].x = xv0 };
C99标准草案
这并不是特别有启发性的,只是为了满足我自己的好奇心:WG14/N1256 C99标准草案
6.7.8 Initialization
designator-list: designator designator-list designator designator: [ constant-expression ] . identifier
Constraints
6 If a designator has the form
[ constant-expression ]
then the current object (defined below) shall have array type and the expression shall be an integer constant expression. If the array is of unknown size, any nonnegative value is valid.
7 If a designator has the form
. identifier
then the current object (defined below) shall have structure or union type and the identifier shall be the name of a member of that type.
Semantics
17 Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.129) In contrast, a designation causes the following initializer to begin initialization of the subobject described by the designator. Initialization then continues forward in order, beginning with the next subobject after that described by the designator
18 Each designator list begins its description with the current object associated with the closest surrounding brace pair. Each item in the designator list (in order) specifies a particular member of its current object and changes the current object for the next designator (if any) to be that member.131) The current object that results at the end of the designator list is the subobject to be initialized by the following initializer.
EXAMPLE 9 Arrays can be initialized to correspond to the elements of an enumeration by using designators:
enum { member_one, member_two }; const char *nm[] = { [member_two] = "member two", [member_one] = "member one", }
EXAMPLE 11 Designators can be used to provide explicit initialization when unadorned initializer lists might be misunderstood:
struct { int a[3], b; } w[] = { [0].a = {1}, [1].a[0] = 2 };