考虑一个C结构:
struct T {
int x;
int y;
};
在
中部分初始化时struct T t = {42};
t.y 保证为0或者这是编译器的实现决定吗?
答案 0 :(得分:27)
如果它被部分初始化,它保证为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.
答案 1 :(得分:27)
标准草案第8.5.1.7项:
-7-如果列表中的初始化程序少于该成员中的成员 聚合,然后每个成员不 明确初始化应为 default-initialized(dcl.init)。 [实施例:
struct S { int a; char* b; int c; }; S ss = { 1, "asdf" };
使用1,ss.b初始化ss.a “asdf”和ss.c,其值为 int()形式的表达式,即 0.]
答案 2 :(得分:3)
没有。它保证为0。