Start learning free

LESSON 106 OF 667 · ARRAYS I

Exceeding static array's bounds in C++

Lesson

When accessing array data with indices, the most common problem we can run into is exceeding the array's bounds.

Remember, the items of an array are indexed from 0 to length - 1. Any index which is not in this range is invalid.

When you try to access an item with an invalid index, C++ doesn't throw an error, but simply returns a random value:

int myArray[] = {50, 40, 30};

// Valid indices: 0, 1, 2
cout << myArray[0] << endl; // Output: 50
cout << myArray[2] << endl; // Output: 30

// Invalid indices: 3, 30, -1
cout << myArray[3] << endl; // random value like 1261279744
cout << myArray[30] << endl; // random value like 1276947770
cout << myArray[-1] << endl; // random value like -2712947770

As programmers, we always want to make sure that we don't exceed one array's bounds in our programs.


Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check