Subscript Operator

A postfix-expression followed by the subscript operator, [ ], specifies array indexing. One of the expressions must be of pointer or array type — that is, it must have been declared as type* or type[ ]. The other expression must be of an integral type (including enumerated types). In common usage, the expression enclosed in the brackets is the one of integral type, but that is not strictly required. Consider the following example:

MyType m[10];     // Declare an array of a user-defined type.

MyType n1 = m[2]; // Select third element of array.
MyType n2 = 2[m]; // Select third element of array.

In the preceding example, the expression m[2] is identical to 2[m]. Although m is not of an integral type, the effect is the same. The reason that m[2] is equivalent to 2[m] is that the result of a subscript expression e1[ e2 ] is given by:

*( (e2) + (e1) )

The address yielded by the expression is not e2 bytes from the address e1. Rather, the address is scaled to yield the next object in the array e2. For example:

double aDbl[2];

The addresses of aDb[0] and aDb[1] are 8 bytes apart — the size of an object of type double. This scaling according to object type is done automatically by the C++ language and is defined in Additive Operators where addition and subtraction of operands of pointer type is discussed.