Why does this array have all other values ​​initialized to zero?

Hello, I am new to C programming language , recently I started to study arrays . I learned that by default, all values ​​in an int array are garbage .

Then why do I get different values ​​in these two cases.

Case-1

int arr[5]; 

in this case from arr [0] to arr [4] we will have garbage values, but in the following case.

Case-2

 int arr[5] = {1}; 

in this case, arr [0] will have the value 1 and the remaining from arr [1] to arr [4] will have the value 0.

My question is that when in case-1, each uninitialized array location has valeus garbage, then why in case the remaining uninitialized cells of array-2 have a value of 0 by default.

+4
source share
4 answers

C11 6.7.9 Initializing p19 covers this (my emphasis)

Initialization must be performed in the order of the list of initializers, each initializer provided for a specific subobject redefines any previously specified initializer for the same subobject; 151) all subobjects that are not initialized explicitly must be implicitly initialized the same as objects with a static storage duration .

Section 6.7.9 p10 states that

If an object that has a static or storage duration of threads is not initialized explicitly, then ... if it has an arithmetic type, it is initialized (positive or unsigned) to zero;

+11
source

Project C99 says:

If the list enclosed in curly brackets contains fewer initializers than elements or elements of the population or fewer characters in the string literal used to initialize an array of known sizes than there are elements in the array, the rest of the population must be initialized implicitly in the same way as objects having a static storage duration.

And static objects are initialized to zero.

So, there is a big difference between the lack of an initializer, which gives you the uninitialized contents of the memory (what you call "garbage"), and having an initializer. If there is an initializer but no data, by default you get 0.

This is very convenient, as it allows you to 0-initialize a large array, doing the same as you.

+8
source

Invalid bit: if you initialize only one element of the array, the rest of its elements will be automatically initialized to 0. The language is determined in this way.

+4
source

from standard C, as indicated here (here you can find even more useful information there)

If the list enclosed in curly brackets contains fewer initializers than there are elements or elements of the population or fewer characters in the string literal used to initialize an array of known size than there are elements in the array, the rest of the population must be initialized implicitly in the same way. as objects having a static storage duration.

+1
source

Source: https://habr.com/ru/post/1490289/


All Articles