C++ brace initialization for integer array

140 views Asked by At

Why does brace-enclosed initialization not work for this integer array?

#include <iostream>
int main()
{
    int arr[2] = {0};
    for (int i = 0; i <= 2; i++)
        std::cout << arr[i] << " ";
}

The output is 0 0 -731153664. Why isn't it 0 0 0?

1

There are 1 answers

0
john On BEST ANSWER

Because there's only two elements in the array

for (int i = 0; i < 2; i++)

Printing arr[2] is undefined behaviour