4

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)

3
  • 3
    You don't get random values for c. You get what's actually in memory at c addresses Commented Feb 18, 2019 at 15:17
  • @JohnH it's not actually shorthand, see answers and duplicate. Commented Feb 18, 2019 at 15:20
  • 2
    Another duplicate here: stackoverflow.com/questions/15520880/… Commented Feb 18, 2019 at 15:26

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.