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 or results are unpredictable. The following code illustrates this concept:
#include <iostream.h>
void main()
{
int iNumberArray[1024];
int *iNumberLine = &iNumberArray[512];
cout << iNumberArray[-256] << "\n"; // Unpredictable
cout << iNumberLine[-256] << "\n"; // OK
}
The negative subscript in iNumberArray
can produce a run-time error because it yields an address 256 bytes lower in memory than the origin of the array. The object iNumberLine
is initialized to the middle of iNumberArray
; it is therefore possible to use both positive and negative array indexes 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 index[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.