C++ – Why Does the First Element Outside of a Defined Array Default to Zero?

arraysc++initializationundefined-behaviorzero-initialization

I'm studying for the final exam for my introduction to C++ class. Our professor gave us this problem for practice:

Explain why the code produces the following output: 120 200 16 0

using namespace std;
int main()
{
  int x[] = {120, 200, 16};
  for (int i = 0; i < 4; i++)
    cout << x[i] << " ";
}

The sample answer for the problem was:

The cout statement is simply cycling through the array elements whose subscript is being defined by the increment of the for loop. The element size is not defined by the array initialization. The for loop defines the size of the array, which happens to exceed the number of initialized elements, thereby defaulting to zero for the last element. The first for loop prints element 0 (120), the second prints element 1 (200), the third loop prints element 2 (16) and the forth loop prints the default array value of zero since nothing is initialized for element 3. At this point i now exceeds the condition and the for loop is terminated.

I'm a bit confused as to why that last element outside of the array always "defaults" to zero. Just to experiment, I pasted the code from the problem into my IDE, but changed the for loop to for (int i = 0; i < 8; i++). The output then changed to 120 200 16 0 4196320 0 547306487 32655. Why is there not an error when trying to access elements from an array that is outside of the defined size? Does the program just output whatever "leftover" data was there from the last time a value was saved to that memory address?

Best Answer

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.

Related Question