Unbreakable
Unbreakable

Reputation: 8084

Array Initialization confusion

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.

Upvotes: 0

Views: 83

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117856

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

Upvotes: 3

Related Questions