未初始化的struct成员是否始终设置为零?

考虑一个C结构:

struct T { int x; int y; }; 

当这部分初始化时,如

 struct T t = {42}; 

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

标准草案第8.5.1.7项:

-7-如果列表中的初始值设定项少于聚合中的成员,则未明确初始化的每个成员应默认初始化(dcl.init)。 [例:

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

使用“asdf”初始化ss.a,使用“asdf”初始化ss.b,使用int()forms的表达式的值初始化ss.c,即0.

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

 struct T t; // tx, ty will NOT be initialized to 0 (not guaranteed to) struct T t = {42}; // ty will be initialized to 0. 

同理:

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

样品:

 // ac 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 ac // as: ; ... partialInitialzation: ; ... ; movl $0, -4(%ebp) ;;;; initializes ty to 0. ; movl $42, -8(%ebp) ; ... noInitialization: ; ... ; Nothing related to initialization. It just allocates memory on stack. 

不,它保证为0。