Are the members of a global structure initialized to zero by default in C?

后端 未结 5 1770
星月不相逢
星月不相逢 2020-12-04 22:21

Are the members of a global or static structure in C guaranteed to be automatically initialized to zero, in the same way that uninitialized global or static variables are?

5条回答
  •  抹茶落季
    2020-12-04 22:43

    Local variables are not initialized.

    struct foobar {
        int x;
    };
    
    int main(void) {
        struct foobar qux;
        /* qux is uninitialized. It is a local variable */
        return 0;
    }
    

    static local variables are initialized to 0 (zero)

    struct foobar {
        int x;
    };
    
    int main(void) {
        static struct foobar qux;
        /* qux is initialized (to 0). It is a static local variable */
        return 0;
    }
    

    Global variables are initialized to 0 (zero)

    struct foobar {
        int x;
    };
    struct foobar qux;
    /* qux is initialized (to 0). It is a global variable */
    
    int main(void) {
        return 0;
    }
    

提交回复
热议问题