Search code examples
c++arraysfor-loopcodeblocks

This 'for' loop prints '1' instead of an array value


Why does this...

int a[5];
a[-2] = 1;
a[-1] = 2;
a[0] = 3;
a[1] = 4;
a[2] = 5;

cout << a[-2] << endl <<endl;

for(int i=-2 ; i<=2 ; i++)
{
    cout << a[i] << endl;
}

...output this?

1

-2
2
3
4
5

I created another project file in Code::Blocks, compiled, and got this:

1

1
-1
3
4
5

I tried to find posts with similar problems, but I couldn’t find any. This just doesn’t make sense to me.


Solution

  • Accessing arrays in C++ using negative indices is undefined behavior, the valid index for:

    int a[5];
    

    will be 0 to 4.

    If we look at the draft C++ standard section 8.3.4 Arrays in paragraph 1 says:

    [...] If the value of the constant expression is N, the array has N elements numbered 0 to N-1, [...]