Why there are Random numbers in non initialized array but not in non initialized members of half initialized array in C++?

Viewed 171

Why in example 1 code it assigns 0s in non initialized items of array, but in example 2 assigns random numbers in completely non initialized array? Why it dont assign 0s to completely non initialized array as well?

Example 1:

int ar[5] ={0,1};
for (int i =0; i< 5; i++){
   cout << ar[i] << " ";
}
// output: 0 1 0 0 0 

Example 2:

int ar[5] ;
for (int i =0; i< 5; i++){
   cout << ar[i] << " ";
}
// output: 1875998720 0 1875947552 0 1876031856 
2 Answers

They're two different initializations.

The case 2, int ar[5]; performs default initialization, as the effect all the elements are initialized to indeterminate values.

The case 1, int ar[5] ={0,1}; performs aggregate initialization, as the effect the 1st and 2nd element are initialized as 0 and 1, the remaining elements are value-initialized (zero-initialized) as 0.

In first Example ! You are initializing the array of size 5 with default values.

int arr[5] = {0,1}

values in curly braces will be assigned to the corresponding index in the array. For example 0 from at the first index of array, 1 at the second index and then default 0 values to the rest of the indexes in array.

In Second Example You are just declaring the array but not initializing. Therefor, at every index of the array, there is garbage value and when you iterate the array you receive unexcepted (garbage) value at each index of the array.

If you declare a variable but don't initialize with any value, it assign the random garbage value that we can't predict.

Related