Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unassigned value in the int[ ]

Tags:

c++

visual-c++

Would like to know in C++ what the value of unassigned integer in an int[] usually is.

Example

int arr[5];
arr[1]=2;
arr[3]=4;
for(int i=0;i<5;i++)
{
  cout <<arr[i] <<endl;
}

it print

-858993460
2
-858993460
4
-858993460

we know that the array will be {?,2,?,4,?} ,where ? is unknown.

What will the "?" be usually?

When I tested , I always got negative value. Can I assume in C++ unassigned element in the integer array is always less than or equal to zero?

Correct me if I'm wrong. When I study in Java unassigned element in array will produce null.

like image 622
Yuvin Ng Avatar asked Jan 13 '23 20:01

Yuvin Ng


1 Answers

Formally, in most cases the very attempt to read an uninitialized value results in undefined behavior. So, formally the question about the actual value is rather moot: you are not allowed to even look at that value directly.

Practically, uninitialized values in C and C++ are unpredictable. On top of that they are not supposed to be stable, meaning that reading the same uninitialized value several times is not guaranteed to read the same value.

If you need a pre-initialized local array, declare it with an explicit initializer

int arr[5] = {};

The above is guaranteed to fill the array with integer zeros.

like image 171
AnT Avatar answered Jan 21 '23 16:01

AnT