Look the following code:
int arr[4];
for (int index = 0; index < 4; ++index) {
printf("%d\t", arr[index]);
}
It print the random values, like this:
27224 -6784 32766 0
But when I set arr
to {}
, It print zeros instead.
int arr[4] = {};
for (int index = 0; index < 4; ++index) {
printf("%d\t", arr[index]);
}
0 0 0 0
Why?
By default, the array elements are uninitialized, which means they will contain garbage values:
int arr[4];
Using a curly brace initializer, you can set the initial values explicitly, e.g.
int arr[4] = {1, 2, 3, 4};
But if the number of numbers in the braces is less than the length of the array, the rest are filled with zeroes. That's what's going on in this case:
int arr[4] = {};
Note that this is not valid in C, only in C++, but your compiler apparently allows it anyway. In standard C, you must write at least one value:
int arr[4] = {0};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With