This happens because of partial array initialization rules in C
How Partial Initialization Works?
When an array is partially initialized, the remaining elements are automatically set to 0
This follows the C standard (C99 and later), which ensures that any missing elements in an initializer list are set to zero
The equivalent explicit initialization would be:
int arr[5] = {1, 2, 3, 0, 0};
What If You Don’t Initialize At All?
int arr[5]; // Uninitialized array
Key Takeaway:
Partial initialization fills remaining elements with 0
Uninitialized arrays contain garbage values
To explicitly zero out an array, use {0}
:
int arr[5] = {0}; // All elements set to 0