What can happen when a C++ program accesses an array element outside its valid bounds?

Options

  • A. It is guaranteed to return zero
  • B. It results in undefined behavior
  • C. The compiler always automatically corrects the index
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

B. It results in undefined behavior

Detailed Explanation

Answer: (B) It results in undefined behavior

Accessing an array outside its valid range can result in undefined behavior.

For example:

int a[5];

The valid indexes are 0 through 4. Accessing a[5] is outside the array.

C++ does not automatically guarantee that such an access will produce an error or return zero. The program may produce an unexpected result, corrupt memory, or behave in other unpredictable ways.