【发布时间】:2017-02-20 03:19:45
【问题描述】:
自定义类型的 C 数组中的独立方括号是什么意思?
typedef enum {
BAR_1 = 0,
BAR_2,
BAR_3,
} bar_types;
typedef struct {
int is_interesting;
int age;
} foo_s;
static foo_s bars[] = {
[BAR_1] = {1, 2}, /* What is being done here? */
[BAR_2] = {1, 41},
[BAR_3] = {0, 33},
};
上面代码中[BAR_1] = {1, 2}是什么意思?什么时候可以使用独立的方括号?
我注意到,如果我在括号中添加重复值,clang 会发出有关子对象初始化的警告。
static foo_s bars[] = {
[BAR_1] = {1, 2},
[BAR_2] = {1, 41},
[BAR_3] = {0, 33},
[BAR_3] = {0, 33},
};
-----
$clang example.c
example.c:17:19: warning: subobject initialization
overrides initialization of other fields within its
enclosing subobject [-Winitializer-overrides]
[BAR_3] = {0, 33},
^~~~~~~
什么是 C 子对象?
【问题讨论】:
-
那些只是指定要初始化的特定数组元素。枚举值的作用类似于对应的
int值,因此[BAR_1] = {1, 2}变为[0] = {1, 2},这意味着数组中的第一个结构(索引0)被初始化为is_interesting为1,age为2。 -
“子对象”是包含在另一个对象中的任何对象。
-
符号是“指定初始化器”的一种。
-
@racraman 这是一个 C++ 问题。这是关于 C 的。