c++ - C数组文字中的显式索引?

标签 c++ c

Linux 内核源码有很多这样的数组字面量:

enum {
  FOO,
  BAR
};

static const char* const names[] = {
  [FOO] = "foo", /* wtf is this? */
  [BAR] = "bar",
};

这里的每一行都明确指出了所提供值在数组中的索引,而不是依赖于排序。

我不知道要搜索的短语 - 这叫什么?是什么标准定义的? (或者它是一个 GNU 扩展?)我可以用 C++ 还是纯 C 来做这个?用 gcc 做实验,我发现上面的 test.c

$ gcc --version
gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE

这些命令返回成功:

$ gcc -Wall -c test.c
$ gcc -Wall -c --std=c90 test.c
$ gcc -Wall -c --std=gnu90 test.c
$ gcc -Wall -c --std=iso9899:1990 test.c
$ gcc -Wall -c --std=c1x test.c

这些命令因各种有关 lambda 和 operator= 的投诉而失败:

$ g++ -Wall -c test.c
$ g++ -Wall -c --std=c++98 test.c
$ g++ -Wall -c --std=gnu++98 test.c
$ g++ -Wall -c --std=c++0x test.c
$ g++ -Wall -c --std=gnu++0x test.c

这表明这是有效的 C(几乎在任何方言中)但不是 C++。但我持怀疑态度。我不记得在 Linux 内核之外的任何地方看到过这个。我也没有看到它在例如 this list of constructs valid in C but not C++ 中描述。 .

最佳答案

它是标准 C(C99 和更新版本)的一部分,称为“指定初始化”。

来自 6.7.9 初始化,第 6 段:

If a designator has the form

[ constant-expression ]

then the current object ... 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.

第 33 段:

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

根据answers at this question , C++ 不支持相同的行为。您的编译器可能会提供扩展。

GCC documentation 可能对您更有帮助(并且直接回答您的问题) ,上面写着:

In ISO C99 you can give the elements in any 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. This extension is not implemented in GNU C++.

关于c++ - C数组文字中的显式索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17581074/

相关文章:

c - C 中的函数指针 - 性质和用法

c++ - 如何使用 openCV 检测图像中的字母?

C++读取文件,数组变量矩阵

c++ - 将两个一维直方图合并为一个

C++ 多态性 - 继承类的映射

c - 未使用计算值

c++ - 错误 C2440 : '=' : cannot convert from 'bool' to 'bool *'

c++ - 在构造函数中使用 'new'? C++

c - OpenCL for 循环给出 CL_OUT_OF_RESOURCES

c - strchr() 在看似没有的地方找到 '\n'