Why does the first element outside of a defined array default to zero?

I’m a bit confused as to why that last element outside of the array
always “defaults” to zero.

In this declaration

int x[] = {120, 200, 16};

the array x has exactly three elements. So accessing memory outside the bounds of the array invokes undefined behavior.

That is, this loop

 for (int i = 0; i < 4; i++)
 cout << x[i] << " ";

invokes undefined behavior. The memory after the last element of the array can contain anything.

On the other hand, if the array were declared as

int x[4] = {120, 200, 16};

that is, with four elements, then the last element of the array that does not have an explicit initializer will be indeed initialized to zero.

Leave a Comment