I declared an array in C like this:
#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 array to be fully initialized with garbage values or maybe some random numbers in the uninitialized places. But instead, the output is:
1 2 3 0 0
Why does C automatically fill the remaining elements with 0 instead of leaving them uninitialized?
Section 6.7.11 says:
- 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
.