Search code examples
c++arraysloopsindexoutofboundsexception

Why am I NOT getting an out of bound array error when iterating through it?


So I set up a simple array and iterate through it. For each element, array[i] is filled with a value of 100. I do i < 4 because obviously array[5] doesn't exist for an array OF FIVE ELEMENTS.

If arrays index at 0, why is the compiler NOT freaking out at me? array[5] shouldn't exist...

using namespace std;

int main()
{
    int array[5];
    for (int i = 0; i < 5; i++)
    {
        array[i] = 100;
    }

    for (int i = 0; i < 5; i++)
    {
        cout << array[i] << "\n";
    }
}

Solution

  • If i < 5 then it must be 4 or less, meaning the maximum is array[4], which is not out of bounds.

    I think you must have confused it with doing i <= 5 which you also see a lot of.