0

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.

Community
  • 1
  • 1
Unbreakable
  • 7,776
  • 24
  • 90
  • 171

1 Answers1

3

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].

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 1
    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! – Unbreakable Jan 02 '15 at 14:23