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.

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.