I have gone through [question 1] (Initialization of a normal array with one default value) and [question 2] (How to initialize an array in C++ objects) But I could not understand below behaviour.
int main()
{
int arr[5];
arr[5] = {-1}; // option 1
int arr1[5] = { -1 }; //option 2
for (int i = 0; i < 5; i++)
cout << arr[i] << " ";
for (int i = 0; i < 5; i++)
cout << arr1[i] << " ";
}
Option 1 gives : GARBAGE VALUES Option 2 gives values : AS EXPECTED Please explain in simple terms why I don't see the same behaviour in both option 1 and option2.
asked Jan 2, 2015 at 14:15
Unbreakable
8,17224 gold badges111 silver badges192 bronze badges
1 Answer 1
In option 1, you are have an uninitialzed array
int arr[5];
Then you assign a value out of bounds
arr[5] = {-1};
since the only valid indicies are [0] to [4].
answered Jan 2, 2015 at 14:18
Cory Kramer
119k19 gold badges177 silver badges233 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Unbreakable
I did that by mistake which you must have understood why because I was thinking totally wrong. But your answer made me understand that I am assigning values to indices not initializing like in option 2. Thanks!
lang-cpp