3

I tried the following code:

int a[4] = {0};
int b[4] = {5};
int c[4];
printf("%d %d %d %d %d %d\n", a[0], a[3] , b[0], b[3], c[0], c[3]);

And got the following result:

0 0 5 0 random random

While I get why I got random values for the c array, I don't understand why the assignation {5} does not work as {0} and only initialize the first element of the array.

Is there a way to initialize array b elements to the same value different from 0? (without using a memset, or a for loop)

Blaze
  • 16,736
  • 2
  • 25
  • 44
Stoogy
  • 1,307
  • 3
  • 16
  • 34

2 Answers2

6

int a[4] = {0}; is actually misleading. It doesn't mean "initialize all elements to 0", it means "initialize the first element to 0 and the rest to its default value", and the rest is then initialized to 0, resulting in all zeros.

Likewise int b[4] = {5}; initializes the first element to 5 and the rest to 0, so you get 5 0 0 0.

The documentation says this:

All array elements that are not initialized explicitly are initialized implicitly the same way as objects that have static storage duration.

And for char, this implicit initialization sets them to 0.

Blaze
  • 16,736
  • 2
  • 25
  • 44
3

When an array initializer has fewer elements than the array, the given initializers are applied in order and any remaining array elements are initialized to 0. So in your case b[0] gets set to 5 and the rest get set to 0.

It "seems" to work for the 0 case because that value is the same as the default.

dbush
  • 205,898
  • 23
  • 218
  • 273