问题描述
以下代码的含义是什么?代码来自 GCC 的回归测试套件.
static char * name[] = {[0x80000000] = "条"};
在 C99 中你可以指定数组索引来赋值,例如:
static char * name[] = {[3] = "酒吧"};
等同于:
static char * name[] = { NULL, NULL, NULL, "bar"};
数组的大小是四.检查在 ideaone 上工作的示例代码.在您的代码数组中,大小为 0x80000001
(它是一个十六进制数).
注意:使用 0
初始化的未初始化元素.
5.20 指定初始化器::H3>
在 ISO C99 中,您可以按任何顺序给出元素,指定它们适用的数组索引或结构字段名称,GNU C 也允许将其作为 C89 模式下的扩展.此扩展未在 GNU C++ 中实现.要指定数组索引,请在元素值之前写入 [index] =
.例如,
int a[6] = { [4] = 29, [2] = 15 };
相当于
int a[6] = { 0, 0, 15, 0, 29, 0 };
在 GNU 扩展中可能还有一个更有趣的声明:
自 GCC 2.5 以来已经过时但 GCC 仍然接受的另一种替代语法是在元素值之前写入 [index]
,没有 =
.>
要将一系列元素初始化为相同的值,请编写 [first ... last] = value
.例如,
int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 };
注意:数组的长度是指定的最大值加一.
此外,我们可以将这种命名元素的技术与连续元素的普通 C 初始化结合起来.每个没有指示符的初始化元素适用于数组或结构的下一个连续元素.例如:
int a[6] = { [1] = v1, v2, [4] = v4 };
相当于
int a[6] = { 0, v1, v2, 0, v4, 0 };
当索引是字符或属于枚举类型时,标记数组初始值设定项的元素特别有用.例如:
int whitespace[256] = { [' '] = 1, ['\t'] = 1, ['\h'] = 1,['\f'] = 1, ['\n'] = 1, ['\r'] = 1};
What is the meaning of following Code? Code is from the regression test suite of GCC.
static char * name[] = {
[0x80000000] = "bar"
};
In C99 you can specify the array indices to assigned value, For example:
static char * name[] = {
[3] = "bar"
};
is same as:
static char * name[] = { NULL, NULL, NULL, "bar"};
The size of array is four. Check an example code working at ideaone. In your code array size is 0x80000001
(its an hexadecimal number).
Note: Uninitialized elements initialized with 0
.
One more interesting declaration is possible in a GNU extension:
Note: that the length of the array is the highest value specified plus one.
Additionally, we can combine this technique of naming elements with ordinary C initialization of successive elements. Each initializer element that does not have a designator applies to the next consecutive element of the array or structure. For example:
int a[6] = { [1] = v1, v2, [4] = v4 };
is equivalent to
int a[6] = { 0, v1, v2, 0, v4, 0 };
Labeling the elements of an array initializer is especially useful when the indices are characters or belong to an enum type. For example:
int whitespace[256] = { [' '] = 1, ['\t'] = 1, ['\h'] = 1,
['\f'] = 1, ['\n'] = 1, ['\r'] = 1
};
这篇关于奇怪的数组初始化表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!