未初始化的结构成员是否总是设置为零?

新手上路,请多包涵

考虑一个 C 结构:

 struct T {
    int x;
    int y;
};

当它被部分初始化时

struct T t = {42};

ty 是否保证为 0 或者这是编译器的实现决定?

原文由 VoidPointer 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 358
2 个回答

标准草案第8.5.1.7项:

-7- 如果列表中的初始化器少于聚合中的成员,则每个未显式初始化的成员都应默认初始化(dcl.init)。 [例子:

 struct S { int a; char* b; int c; };
S ss = { 1, "asdf" };

用 1 初始化 ss.a,用“asdf”初始化 ss.b,用 int() 形式的表达式的值(即 0)初始化 ss.c。]

原文由 bayda 发布,翻译遵循 CC BY-SA 2.5 许可协议

如果它被部分初始化,它保证为 0,就像数组初始化器一样。如果它未初始化,它将是未知的。

 struct T t; // t.x, t.y will NOT be initialized to 0 (not guaranteed to)

struct T t = {42}; // t.y will be initialized to 0.

相似地:

 int x[10]; // Won't be initialized.

int x[10] = {1}; // initialized to {1,0,0,...}

样本:

 // a.c
struct T { int x, y };
extern void f(void*);
void partialInitialization() {
  struct T t = {42};
  f(&t);
}
void noInitialization() {
  struct T t;
  f(&t);
}

// Compile with: gcc -O2 -S a.c

// a.s:

; ...
partialInitialzation:
; ...
; movl $0, -4(%ebp)     ;;;; initializes t.y to 0.
; movl $42, -8(%ebp)
; ...
noInitialization:
; ... ; Nothing related to initialization. It just allocates memory on stack.

原文由 mmx 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题