Reputation: 105
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
?
Upvotes: 0
Views: 147
Reputation: 88092
Because there's only two elements in the array
for (int i = 0; i < 2; i++)
Printing arr[2]
is undefined behaviour
Upvotes: 1