Positive and Negative Subscripts

The first element of an array is element 0. The range of a C++ array is from array[0] to array[size – 1]. However, C++ supports positive and negative subscripts. Negative subscripts must fall within array boundaries; if they do not, the results are unpredictable. The following code shows positive and negative array subscripts:

#include <iostream>
using namespace std;

int main() {
    int intArray[1024];
    for (int i = 0, j = 0; i < 1024; i++)
    {
        intArray[i] = j++;
    }

    cout << intArray[512] << endl;// 512
   
    int *midArray = &intArray[512];  // pointer to the middle of the array

    cout << midArray[-256] << endl;   // 256

    cout << intArray[-256] << endl; // unpredictable
}

The negative subscript in the lasta line can produce a run-time error because it points an address 256 bytes lower in memory than the origin of the array. The pointer midArray is initialized to the middle of intArray; it is therefore possible to use both positive and negative array indices on it. Array subscript errors do not generate compile-time errors, but they yield unpredictable results.

The subscript operator is commutative. Therefore, the expressions array[index] and array[array] are guaranteed to be equivalent as long as the subscript operator is not overloaded (see Overloaded Operators). The first form is the most common coding practice, but either works.

See Also

Reference

Postfix Expressions