arrayscinitializationlist-initialization

Why does C zero-fill remaining elements when partially initializing an array?


I declared an array in Cas:

#include <stdio.h>

int main() {
    int arr[5] = {1, 2, 3};  
    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

I expected the last two elements to have garbage values, similar to uninitialized local variables, but the output is:

1 2 3 0 0

Why does the C standard zero-initialize the remaining elements of an array when partially initialized? Is this behavior different between local and global arrays, or in different contexts?


Solution

  • Section 6.7.11 says:

    1. 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 is subject to default initialization.

    And the definition of default initialization is in paragraph 11 of the same section; for int, it says that they will be set to 0.