Search code examples
cstringinitialization

What does initializing a string to {0, } do?


I've seen code like this:

char str[1024] = {0, };

and suspect that it is similar to doing this:

char str[1024];
str[0] = '\0';

But I couldn't find anything on it so I'm not sure.

What is this (called) and what does it do?


Disclaimer: I'm aware this might have been asked and answered before, but searching for {0, } is astonishingly hard. If you can point out a duplicate, I'll happily delete this question.


Solution

  • No, they are not the same.

    This statement

    char str[1024] = {0, };
    

    initializes the first element to the given value 0, and all other elements are to be initialized as if they have static storage, in this case, with a value 0. Syntactically this is analogous to using

    char str[1024] = {0};
    

    Quoting C11, chapter 6.7.9, p21

    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, from p10 (emphasis mine)

    If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

    • if it has pointer type, it is initialized to a null pointer;

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

    • if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

    • if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

    On the other hand

    char str[1024];
    str[0] = '\0';
    

    only initializes the first element, and the remaining elements remains unitialized, containing indeterminate values.