C99结构指定Initialisers等价值 [英] C99 Structure Designated Initialisers and other value

查看:430
本文介绍了C99结构指定Initialisers等价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,在C99中你可以使用初始化成员名称结构的成员如下:

I am aware that in C99 you can initialize members of the structure using member name as follows :

struct myStruct
{
 int i;
 char c;
 float f;
};

所以,以下是有效的:

So following is valid :

struct myStruct m = {.f = 10.11, .i = 5, .c = 'a'};

也有人说,未初始化的成员将被设置为 0 。因此,

struct myStruct m = {.f = 10.11, .c = 'a'};

在这里 I 将被设置为 0

但是,对于以下内容:

struct myStruct m = {.f = 10.11, .c = 'a', 6}; 

I 仍然初始化为0。什么是如果我们做这样的化合物初始化的原因。

i is still initialized to 0. What is the reason if we do such compound initialization.

推荐答案

这是覆盖在C99的标准草案 6.7.8 初始化的,基本上如果下面的初始化不是一个标志那么它会是代号拿起后下一个领域,这对于你的例子是˚F。大家可以看一下段落的 17 的它说(的重点煤矿的):

This is covered in the draft C99 standard section 6.7.8 Initialization, basically if the following initializer is not a designator then it will pick up with the next field after that designator, which for your examples would be f. We can look at paragraph 17 which says (emphasis mine):

每个大括号内的初始化列表有一个相关的当前对象。
  如果没有指定值为present,当前对象的子对象
  根据当前对象的类型初始化顺序:
  增加下标顺序数组元素,结构成员
  声明顺序和union.129的第一个命名成员)在
  相反,的指定导致以下初始化开始
  由标志所描述的子对象的初始化。
  初始化然后继续前进,才能,较年初
  之后由标志说明下一子对象
.130)

Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.129) In contrast, a designation causes the following initializer to begin initialization of the subobject described by the designator. Initialization then continues forward in order, beginning with the next subobject after that described by the designator.130)

为什么 I 初始化为 0 是覆盖在paragrah的 19 的其中说:

Why i is initialized to 0 is covered in paragrah 19 which says:

初​​始化应发生在初始化列表中的顺序,每个
  初始化提供了一个特定的子对象覆盖所有
  previously上市初始化为相同的子对象; 132)所有
  未明确初始化子对象应被初始化
  隐含一样具有静态存储持续时间的对象。

The initialization shall occur in initializer list order, each initializer provided for a particular subobject overriding any previously listed initializer for the same subobject;132) all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.

请注意,由于基思指出 GCC 提供了一个警告,这种使用 -Wextra

Note that as Keith points out gcc provides a warning for this using -Wextra:

warning: initialized field overwritten [-Woverride-init]
 struct myStruct m = {.f = 10.11, .c = 'a', 6}; 
        ^

似乎在默认情况下,警告这一点。

and clang seems to warn about this by default.

这篇关于C99结构指定Initialisers等价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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