简体   繁体   English

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

[英]Are uninitialized struct members always set to zero?

Consider a C struct:考虑一个 C 结构:

struct T {
    int x;
    int y;
};

When this is partially initialized as in当它被部分初始化时

struct T t = {42};

is t.y guaranteed to be 0 or is this an implementation decision of the compiler? t.y 是否保证为 0 或者这是编译器的实现决定?

It's guaranteed to be 0 if it's partially initialized, just like array initializers.如果它被部分初始化,它保证为 0,就像数组初始化器一样。 If it's uninitialized, it'll be unknown.如果它未初始化,它将是未知的。

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.

Similarly:相似地:

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

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

Sample:样本:

// 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.

item 8.5.1.7 of standard draft:标准草案第8.5.1.7项:

-7- If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be default-initialized (dcl.init). -7- 如果列表中的初始化器少于聚合中的成员,则每个未显式初始化的成员都应默认初始化(dcl.init)。 [Example: [例子:

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

initializes ss.a with 1, ss.b with "asdf", and ss.c with the value of an expression of the form int(), that is, 0. ]将 ss.a 初始化为 1,将 ss.b 初始化为“asdf”,将 ss.c 初始化为 int() 形式的表达式的值,即 0。]

No. it is guaranteed to be 0.不,它保证为 0。

In addition to the excellent answers above, I also found out that (at least with GCC) you can "partly initialize" a struct without explicitly assigning any member by using {} :除了上述出色的答案之外,我还发现(至少使用 GCC)您可以“部分初始化”一个结构,而无需使用{}显式分配任何成员:

#include <stdio.h>

struct a {
    int x;
    int y;
};

int main() {
    struct a a = {};

    printf ("{.x=%d, .y=%d}\n", a.x, a.y);
    return 0;
}

This prints out: {.x=0, .y=0} .打印出来: {.x=0, .y=0}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM