gpt4 book ai didi

c - 非显式初始化的成员在其部分成员被初始化的结构中始终为 0?

转载 作者:太空宇宙 更新时间:2023-11-04 06:20:39 25 4
gpt4 key购买 nike

我正在验证结构成员初始化。编译器是gcc 4.8.5,代码是这样的:

#include <stdio.h>

typedef struct
{
int m1;
int m2;
} A;

int main(void) {
A a;
A b = {.m1 =1};
A c = {1};

printf("%d, %d\n", a.m1, a.m2);
printf("%d, %d\n", b.m1, b.m2);
printf("%d, %d\n", c.m1, c.m2);
return 0;
}

执行结果为:

-1498088800, 32765
1, 0
1, 0

汇编代码为:

0x0000000000400530 <+0>:     push   %rbp
0x0000000000400531 <+1>: mov %rsp,%rbp
0x0000000000400534 <+4>: sub $0x30,%rsp
0x0000000000400538 <+8>: movq $0x0,-0x20(%rbp)
0x0000000000400540 <+16>: movl $0x1,-0x20(%rbp)
0x0000000000400547 <+23>: movq $0x0,-0x30(%rbp)
0x000000000040054f <+31>: movl $0x1,-0x30(%rbp)
0x0000000000400556 <+38>: mov -0xc(%rbp),%edx
0x0000000000400559 <+41>: mov -0x10(%rbp),%eax
0x000000000040055c <+44>: mov %eax,%esi
0x000000000040055e <+46>: mov $0x400640,%edi
0x0000000000400563 <+51>: mov $0x0,%eax
0x0000000000400568 <+56>: callq 0x400410 <printf@plt>

来自汇编代码:

0x0000000000400538 <+8>:     movq   $0x0,-0x20(%rbp)
0x0000000000400540 <+16>: movl $0x1,-0x20(%rbp)
0x0000000000400547 <+23>: movq $0x0,-0x30(%rbp)
0x000000000040054f <+31>: movl $0x1,-0x30(%rbp)

我可以看到如果我初始化结构的部分成员,其他成员默认设置为0。这是否符合 C 规范?还是只取决于编译器?

最佳答案

它们被授予为零。

引自 N1256 6.7.8 初始化

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules;
— if it is a union, the first named member is initialized (recursively) according to these rules.

21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

关于c - 非显式初始化的成员在其部分成员被初始化的结构中始终为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35765920/

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