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/