空的初始化列表是有效的 C 代码吗? [英] Is an empty initializer list valid C code?
问题描述
通常使用 {0}
来初始化 struct
或 array
但考虑第一个字段不是标量类型.如果 struct Person
的第一个字段是另一个 struct
或数组,那么这一行会导致错误(error: missing brass around initializer
).
It is common to use {0}
to initialize a struct
or an array
but consider the case when the first field isn't a scalar type. If the first field of struct Person
is another struct
or array, then this line will result in an error (error: missing braces around initializer
).
struct Person person = {0};
至少 GCC 允许我使用一个空的初始化列表来完成同样的事情
At least GCC allows me to use an empty initializer list to accomplish the same thing
struct Person person = {};
但这是有效的 C 代码吗?
But is this valid C code?
另外:这一行是否保证提供相同的行为,即零初始化的 struct
?
Also: Is this line guaranteed to give the same behavior, i.e. a zero-initialized struct
?
struct Person person;
推荐答案
否,不允许使用空的初始化列表.使用 -std=c99 -pedantic
编译时,GCC 也可以显示这一点:
No, an empty initializer list is not allowed. This can also be shown by GCC when compiling with -std=c99 -pedantic
:
a.c:4: warning: ISO C forbids empty initializer braces
原因是2011 ISO C 标准:
initializer:
assignment-expression
{ initializer-list }
{ initializer-list , }
initializer-list:
designation(opt) initializer
initializer-list , designation(opt) initializer
根据该定义,一个初始化列表必须至少包含一个初始化.
According to that definition, an initializer-list must contain at least one initializer.
这篇关于空的初始化列表是有效的 C 代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!