Take the 2-minute tour ×

Why 2[a] can be compiled if only declare int a[3] in C.

 1  #include <stdio.h>
 3  int main(int argc, char **argv)
 4  {
 5      int a[3] = {1, 2, 3};
 6      printf("a[2] is: %d\n", a[2]);
 7      printf("2[a] is: %d\n", 2[a]);
 9      return 0;
10  }

And the output both 3, how to explain it?

share|improve this question

3 Answers 3

up vote 12 down vote accepted

Because a[2] is just syntactic sugar for *(a+2), which is the same as *(2+a) or 2[a].

share|improve this answer
Mmmmmm sugar... +1 –  Mehrdad Apr 21 '11 at 2:06
Some would call it syntactic vinegar. :-) –  R.. Apr 21 '11 at 2:22

Because all a[2] means in C is *(a + 2), and so *(2 + a) works just as well, which could also be written 2[a].

share|improve this answer

An expression is composed of one or more operands. The simplest form of an expression consists of a single literal constant or object. The result, in general, is the operand's rvalue.

As per the C standard: Array subscripting

2 A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

So, a[b] is equivalent to *(a+b) and b[a]. where a and b can be any expression.

share|improve this answer

Your Answer


