是一个空的初始化列表有效的C code? [英] Is an empty initializer list valid C code?

查看:95
本文介绍了是一个空的初始化列表有效的C code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是常见的使用 {0} 来初始化结构阵列但是当第一字段是不是标类型考虑的情况下。如果的结构人物第一场是另一个结构或数组,那么这条线会导致错误(错误:缺少初始左右括号

 结构的人的人= {0};

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

 结构的人的人= {};

但是,这是合法的C code?

另外:这是行保证给相同的行为,即一个零初始化结构

 结构的人的人;


解决方案

没有,是不允许空的初始化列表。这也可以通过与GCC编译时使用 -std = C99 -pedantic

 交流转换器:4:警告:​​ISO C不允许空初始化括号

原因是语法中的 2011 ISO C标准的:

 初始化:
         分配-EX pression
         {初始化列表}
         {初始化列表,}
初始化列表:
         指定(OPT)初始化
         初始化列表,指定(OPT)初始化

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

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};

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

struct Person person = {};

But is this valid C code?

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

struct Person person;

解决方案

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

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

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 code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆