lord.garbage
lord.garbage

Reputation: 5960

Default initializion value of boolean member in struct

If I have the following

struct a {
        int a;
        int b;
        bool c;
}

and use the following initialization function

struct ls *ls_new(struct ls **ls, size_t *size)
{
        struct ls *m, *n;
        n = realloc(*ls, (*size + 1) * sizeof(struct ls));
        if (!n)
                return NULL;

        *ls = n;
        m = *ls + *size;
        (*size)++;

        // init struct
        *m = (struct ls) {.a = 0}

        return m;
}

When I use ls_new() to initialize an instance of struct a the c99 standard guarantees that initializing one member of the struct will also initialize all other members. What will be the default initialization value for bool c?

Upvotes: 3

Views: 3969

Answers (1)

ouah
ouah

Reputation: 145839

What will be the default initialization value for bool c?

It is 0, i.e., false.

From:

(C99, 6.7.8p22) "If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration."

and

(C99, 6.7.8p10) "If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then: [...]

— if it has arithmetic type, it is initialized to (positive or unsigned) zero;

And _Bool (which bool macros expands to) is an arithmetic type.

Upvotes: 5

Related Questions