问题描述
我遇到了下面的代码,它以非标准的方式在 C
中声明 char *
数组:
/ *消息类型描述数组* /
char * msgType [M_LAST_MSG] =
{
[M_INIT_MSG]Init,
[M_RESET_MSG]Serdes Reset
};
M_INIT_MSG
, M_RESET_MSG
和 M_LAST_MSG
是相应值为0,1和2的枚举。
根据正式 C
文档中,这个数组中的变量是字符串(文字),那么以这种方式使用这些枚举的目的是什么?是否有任何文档支持它?
用ARM编译 gcc
编译器 gcc-arm-none-eabi
。
此语法允许您通过索引初始化数组的特定元素。您可以使用 int
或 enum
值指定要初始化的数组元素。这样,你指定的值不需要是连续的。
如果你有这样的话:
int x [5] = {[2] 3,[4] 7};
它相当于这个:
int x [5] = {0,0,3,0,7};
在上例中,枚举值指定将数组的元素0和1初始化为Init
和Serdes Reset
。
从:
编辑:
请注意,标准的语法包含一个 =
,而OP的例子没有。没有 =
的语法显然是GCC支持的旧语法。编译OP的例子给出了以下警告:
lockquote
警告:过期使用指定的初始值设定项而不使用'='
I came across the following code which declares char *
array in C
in a non-standard way:
/* Message Type description array */
char *msgType[M_LAST_MSG] =
{
[M_INIT_MSG] "Init",
[M_RESET_MSG] "Serdes Reset"
};
Compiled with ARM gcc
compiler gcc-arm-none-eabi
.
int x[5] = { [2] 3, [4] 7 };
It would be equivalent to this:
int x[5] = { 0, 0, 3, 0, 7 };
From section 6.7.8 of the C99 standard:
EDIT:
Note that the syntax from the standard includes a =
while OP's example does not. The syntax without =
is apparently an old syntax supported by GCC. Compiling OP's example gives the following warning:
The GCC documentation states the following:
这篇关于在C中使用非标准的数组声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!