Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference of "int arr[] = {}" and "int arr[]" in C

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?

like image 952
Jaune Avatar asked Dec 07 '22 10:12

Jaune


1 Answers

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};
like image 67
Thomas Avatar answered Dec 10 '22 00:12

Thomas