4

How this works(sets all values to 0)?

int array[28]= {0};

and why this not works(does not set all values to 4 but only the first value sets to 4 and others to 0)?

int array[28]= {4};
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
NAbdulla
  • 85
  • 7
  • Here is the answer to your question: http://stackoverflow.com/questions/4066522/setting-an-array-to-one-value –  Oct 05 '15 at 11:33

4 Answers4

10

In C, any element not listed in an initializer is implicitly being initialized to it's zero value.

int array[28]= {0}; creates an array of 28 ints, and initializes the first element to 0. The remaining elements are not mentioned in the initializer get their zero value, which is 0 for ints.

int array[28]= {4}; Works similarly. The first element is initialized to 4, and the remaining elements that are not mentioned in the initializer get their zero value.

nos
  • 223,662
  • 58
  • 417
  • 506
10

The elements which are not initialized are set 0. In your first case you are initilizing it by providing it the value as 0 and rest are by default initialized as 0. In your second case the first values is intialized with 4 and rest as 0. The standard says:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
2

Simply because the standard demands it.

ISO/IEC:9899 (c99 standard) TC3 states:

6.7.8 Initialization

[...]

21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

What refers to the same paragraph at point 10: (emphasis mine)

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:

— if it has pointer type, it is initialized to a null pointer;

— if it has arithmetic type, it is initialized to (positive or unsigned) zero;

— if it is an aggregate, every member is initialized (recursively) according to these rules;

— if it is a union, the first named member is initialized (recursively) according to these rules.

So it is simply given that this has to happen, and thats why it happens.

dhein
  • 6,431
  • 4
  • 42
  • 74
1
int array[5] = {0}

All the elements will be initialized to 0

int array[5] = {1,2,3}

In this case first element will be initialized to 1, second to 2, third to 3 and rest of the elements to 0.

cryptomanic
  • 5,986
  • 3
  • 18
  • 30