1

Possible Duplicate:
In C arrays why is this true? a[5] == 5[a]

While coding in C, I accidentally found that the code below correctly prints the elements of array A:

int A[] = {10, 20, 5, 32, 40};

for(int i=0; i<5; i++) 
    printf("%d \n", i[A]);

So i[A] acts likeA[i].

Why? what is the logic behind this behavior?

Community
  • 1
  • 1
Farshad
  • 19
  • 2

2 Answers2

5

Because the subscript operator in C is defined in terms of pointer arithmetic, see

(C99, 6.5.2.1p2) "The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2)))."

ouah
  • 138,975
  • 15
  • 262
  • 325
3

it's commutativity of addition:

*(A+i) same as *(i+A)
triclosan
  • 5,316
  • 6
  • 25
  • 48