Codes / Error Code 009

Error Code 009

Overview

This error occurs when attempting to access an element of an array using an index that is either negative or exceeds the array’s bounds.


Details

  • Common Causes:

    • Using a hardcoded index outside the array’s range.
    • Looping beyond the array’s length.
    • Failing to check array bounds before accessing elements.
  • Example:

void main() {
    int[] arr = [1, 2, 3];
    writeln(arr[3]); // Error: array index out of bounds
}
  • Solution:
    • Use bounds checking before accessing elements:
      void main() {
          int[] arr = [1, 2, 3];
          if (arr.length > 2) {
              writeln(arr[2]); // Safe
          }
      }
    • Iterate within the bounds of the array:
      void main() {
          int[] arr = [1, 2, 3];
          foreach (i, value; arr) {
              writeln("Index ", i, ": ", value); // Safe iteration
          }
      }