什么是 C 中的指定初始化程序?

What is a designated initializer in C?

我知道这可能是一个基本问题。

我有一个作业要求我了解 C 中的指定初始化器是什么以及用指定初始化器初始化变量的含义。

我不熟悉这个术语,找不到任何确定的定义。

什么是 C 中的指定初始化程序?

指定初始化器有两种形式:

1) 它提供了一种快速初始化数组中特定元素的方法:

int foo[10] = { [3] = 1, [5] = 2 };

会将 foo 的所有元素设置为 0,除了将设置为 1 的索引 3 和将设置为 2 的索引 5 之外。

2) 它提供了一种显式初始化 struct 成员的方法。例如,对于

struct Foo { int a, b; };

你可以写

struct Foo foo { .a = 1, .b = 2 };

请注意,在这种情况下,未明确初始化的成员将被初始化,就好像该实例具有 static 持续时间一样。


两者都是标准 C,但请注意,C++ 两者都不支持(因为构造函数可以用该语言完成这项工作。)

Designed Initializer 自 ISO C99 以来就出现了,它是在 C 中初始化 structunionarray 时一种不同且更动态的初始化方式。

与标准初始化的最大区别是您不必按固定顺序声明元素,也可以省略元素。

来自 GNU Guide:

Standard C90 requires the elements of an initializer to appear in a fixed order, the same as the order of the elements in the array or structure being initialized.

In ISO C99 you can give the elements in random order, specifying the array indices or structure field names they apply to, and GNU C allows this as an extension in C90 mode as well


例子

1。数组索引

标准初始化

  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 };

2。结构或联合:

标准初始化

struct point { int x, y; };

设计初始化

 struct point p = { .y = 2, .x = 3 }; or
 struct point p = { y: 2, x: 3 };

3。将命名元素与连续元素的普通 C 初始化相结合:

标准初始化

int a[6] = { 0, v1, v2, 0, v4, 0 };

设计初始化

int a[6] = { [1] = v1, v2, [4] = v4 };

4。其他:

标记数组初始值设定项的元素

int whitespace[256] = { [' '] = 1, ['\t'] = 1, ['\h'] = 1,
                        ['\f'] = 1, ['\n'] = 1, ['\r'] = 1 };

在'='之前写一系列'.fieldname'和'[index]'指示符以指定要初始化的嵌套子对象

struct point ptarray[10] = { [2].y = yv2, [2].x = xv2, [0].x = xv0 };

指南