gpt4 book ai didi

C99 结构指定初始化器和其他值

转载 作者:太空狗 更新时间:2023-10-29 16:35:36 24 4
gpt4 key购买 nike

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

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

所以下面是有效的:

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,这样复合初始化是什么原因。

最佳答案

这在草案 C99 标准部分 6.7.8 Initialization 中有介绍,基本上如果以下初始化程序不是指示符,那么它将在之后的下一个字段中获取该指示符,在您的示例中为 f。我们可以看一下 17 段,它说(强调我的):

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 在段落 19 中有说明:

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.

请注意,正如 Keith 指出的那样,gcc 使用 -Wextra 对此提供了警告:

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

clang 似乎默认对此发出警告。

关于C99 结构指定初始化器和其他值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25386780/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com