carraysarray-initialization

Why {0} assignation works but not {5} for an array


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)


Solution

  • 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.