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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With