Search code examples
ccompiler-construction

How does C compiler declare array when there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate?


This may be a simple question but I am trying to understand how the compiler assigns all the elements in the array to zero for example: ''' array[5] = {0}; '''

I checked gcc.gnu.org for some explanation but was unsuccessful. Maybe I am looking in the wrong location. I also checked C99 and stumbled upon section 6.7.8/21, but it does not tell me how it is initialized. I also looked at other posts about this topic but most address what happens, not how it happens.

Anyway, my questions are:

How does the compiler assign all the elements to zero through this single expression?

Where can I find information on how the compiler works, specifically with the example above?

Thanks...


Solution

  • C 2018 6.7.9 19 says:

    … all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.

    C 2018 6.7.9 10 says, for objects with static storage duration that are not initialized explicitly:

    — 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;

    Thus, when you initialize part but not all of an array, the rules of the C standard require the compiler to initialize the other elements to zero for arithmetic types and a null pointer for pointer types.

    Compilers are free to implement this as they choose. The method is not usually document, and it varies by situation: For a small array, the compiler might generate explicit instructions. For a large array, the compiler might generate a loop (including a single instruction that implements a loop to zero memory) or call a library routine. Or, if the compiler can detect that initialization is not actually necessary for correct program operation, it might omit it. For example, if the compiler can see that a subsequent assignment sets an array element to a value before that array element is used, the compiler might omit any zeroing of the array element and instead let the assignment be the initial value.