考虑一个C结构:
struct T {
int x;
int y;
};
Run Code Online (Sandbox Code Playgroud)
当这部分初始化时,如
struct T t = {42};
Run Code Online (Sandbox Code Playgroud)
是TY保证是0或者这是编译器的实现决定?
Meh*_*ari 28
如果它被部分初始化,它保证为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.
Run Code Online (Sandbox Code Playgroud)
同理:
int x[10]; // Won't be initialized.
int x[10] = {1}; // initialized to {1,0,0,...}
Run Code Online (Sandbox Code Playgroud)
样品:
// 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.
Run Code Online (Sandbox Code Playgroud)
bay*_*yda 27
标准草案第8.5.1.7项:
-7-如果列表中的初始值设定项少于聚合中的成员,则未明确初始化的每个成员都应默认初始化(dcl.init).[例:
Run Code Online (Sandbox Code Playgroud)struct S { int a; char* b; int c; }; S ss = { 1, "asdf" };
使用"asdf"初始化ss.a,使用"asdf"初始化ss.b,使用int()形式的表达式的值初始化ss.c,即0.