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:
// expre_Positive_and_Negative_Subscripts.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
int main() {
int iNumberArray[1024];
int *iNumberLine = &iNumberArray[512];
cout << iNumberLine[-256] << "\n"; // OK
// Unpredictable
// cout << iNumberArray[-256] << "\n";}
}
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 i0.t. 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.
Reference
Postfix Expressions