空的初始化列表是有效的C代码吗?

时间:2021-09-05 22:50:00

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).

通常使用{0}初始化结构或数组,但考虑第一个字段不是标量类型时的情况。如果struct Person的第一个字段是另一个结构或数组,那么这一行将导致错误(错误:初始化器周围缺少大括号)。

struct Person person = {0};

At least GCC allows me to use an empty initializer list to accomplish the same thing

至少GCC允许我使用空的初始化列表来完成同样的事情

struct Person person = {};

But is this valid C code?

但这是有效的C代码吗?

Also: Is this line guaranteed to give the same behavior, i.e. a zero-initialized struct?

另外:这条线是否保证给出相同的行为,即零初始化结构?

struct Person person;

1 个解决方案

#1


31  

No, an empty initializer list is not allowed. This can also be shown by GCC when compiling with -std=c99 -pedantic:

不,不允许使用空的初始化列表。当使用-std = c99 -pedantic进行编译时,GCC也可以显示这一点:

a.c:4: warning: ISO C forbids empty initializer braces

The reason is the way the grammar is defined in §6.7.9 of the 2011 ISO C Standard:

原因是语法在2011 ISO C标准的§6.7.9中定义的方式:

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.

根据该定义,初始化列表必须包含至少一个初始化程序。

#1


31  

No, an empty initializer list is not allowed. This can also be shown by GCC when compiling with -std=c99 -pedantic:

不,不允许使用空的初始化列表。当使用-std = c99 -pedantic进行编译时,GCC也可以显示这一点:

a.c:4: warning: ISO C forbids empty initializer braces

The reason is the way the grammar is defined in §6.7.9 of the 2011 ISO C Standard:

原因是语法在2011 ISO C标准的§6.7.9中定义的方式:

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.

根据该定义,初始化列表必须包含至少一个初始化程序。