Export (0) Print
Expand All

Subscript Operator: []

postfix-expression [ expression ]

A postfix expression (which can also be a primary expression) followed by the subscript operator, [ ], specifies array indexing.

For information about managed arrays, see array (Visual C++).

Usually, the value represented by postfix-expression is a pointer value, such as an array identifier, and expression is an integral value (including enumerated types). However, all that is required syntactically is that one of the expressions be of pointer type and the other be of integral type. Thus the integral value could be in the postfix-expression position and the pointer value could be in the brackets in the expression or subscript position. Consider the following code fragment:

   int nArray[5] = { 0, 1, 2, 3, 4 };
   cout << nArray[2] << endl;            // prints "2"
   cout << 2[nArray] << endl;            // prints "2"

In the preceding example, the expression nArray[2] is identical to 2[nArray]. The reason 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.

A subscript expression can also have multiple subscripts, as follows:

expression1 [expression2] [expression3]...

Subscript expressions associate from left to right. The leftmost subscript expression, expression1[expression2], is evaluated first. The address that results from adding expression1 and expression2 forms a pointer expression; then expression3 is added to this pointer expression to form a new pointer expression, and so on until the last subscript expression has been added. The indirection operator (*) is applied after the last subscripted expression is evaluated, unless the final pointer value addresses an array type.

Expressions with multiple subscripts refer to elements of multidimensional arrays. A multidimensional array is an array whose elements are arrays. For example, the first element of a three-dimensional array is an array with two dimensions. The following example declares and initializes a simple two-dimensional array of characters:

// expre_Subscript_Operator.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;
#define MAX_ROWS 2
#define MAX_COLS 2

int main() {
   char c[ MAX_ROWS ][ MAX_COLS ] = { { 'a', 'b' }, { 'c', 'd' } };
   for ( int i = 0; i < MAX_ROWS; i++ )
      for ( int j = 0; j < MAX_COLS; j++ )
         cout << c[ i ][ j ] << endl;

Community Additions

© 2014 Microsoft