programing

초기화되지 않은 구조 부재는 항상 0으로 설정됩니까?

mailnote 2023. 10. 13. 22:22
반응형

초기화되지 않은 구조 부재는 항상 0으로 설정됩니까?

C 구조를 생각해 보십시오.

struct T {
    int x;
    int y;
};

에서와 같이 부분적으로 초기화된 경우

struct T t = {42};

t.y0이 보장되는 것인가요, 아니면 이것이 컴파일러의 구현 결정인가요?

배열 초기화자와 마찬가지로 부분 초기화된 경우 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.

표준 초안의 항목 8.5.1.7:

-7- 목록에 있는 초기화자의 수가 Aggregate의 구성원 수보다 적을 경우, 명시적으로 초기화되지 않은 각 구성원은 default-initialization(dcl.init)됩니다.[예:

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

ss.a를 1로, s.b를 "asdf"로, s.c를 (), 형식의 값으로 초기화합니다. 즉, 0. ]

아니요. 0으로 보장됩니다.

위의 훌륭한 답변 외에도, 저는 (적어도 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;
}

출력:{.x=0, .y=0}.

언급URL : https://stackoverflow.com/questions/706030/are-uninitialized-struct-members-always-set-to-zero

반응형