1

Check the following C code I wrote. I thought the compiler may complain about i[a], but it actually prints the exact same value as a[i]. How does this happen?

#include <stdio.h>

int main(){
  int a[3] = {0, 1, 2};
  int i;
  for(i = 0; i < 3; i++){
    printf("normal a[%d] = %d\n", i, a[i]);
    printf("abnormal a[%d] = %d\n", i, i[a]);
  }

  return 0;
}

The print out values:

normal a[0] = 0
abnormal a[0] = 0
normal a[1] = 1
abnormal a[1] = 1
normal a[2] = 2
abnormal a[2] = 2
drdot
  • 3,215
  • 9
  • 46
  • 81

1 Answers1

2
  1. a[i] is equivalent to *(a + i)
  2. i[a] is equivalent to *(i + a) which is equivalent to *(a + i)

So, effectively , both are same.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • I know this may be obvious because people are down voting my post. But just to make sure I understand what was going on. To do pointer arithmetic, assuming a is the pointer and i is the index, I can always do i[a] and it always equal to *(a+i)? – drdot Nov 25 '14 at 07:18
  • 1
    @dannycrane People are most likely down-voting your post because it is a common FAQ and they don't think you did enough research before posting the question. As for why it works, check the answers in the duplicate question linked. – Lundin Nov 25 '14 at 07:22