5

Consider the following:

int main() {
        int a[] = {42, 9001, -1337};
        printf("%d, %d\n", a[0], 0[a]);
        return 0;
}

I didn't see 0[a] before, but it appears to do the same as a[0] (the same appears to be true for other numbers as well, not just for 0).

Is that my compiler's fault (GCC)? Is there any documentation on this behavior? What purpose does it serve?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Chiru
  • 3,661
  • 1
  • 20
  • 30

3 Answers3

16

a[0] is the same as *(a+0)
0[a] is the same as *(0+a)

We know that a+0 is same as 0+a.So *(a+0)==*(0+a) which would mean that a[0]==0[a].

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
  • 2
    It was referenced in [r/programminghorror](https://www.reddit.com/r/programminghorror/comments/v7pyc8/comment/ibm1i77/?utm_source=bob&utm_medium=nokia5110), but in a positive way. – kdb Jun 09 '22 at 11:18
5

a[0] is another form of *(a + 0) , which can be rewritten as *(0 + a), which can be rewritten as 0[a]

So, essentially, a[0] and 0[a] represents the same.

There is no fault or error from your compiler.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

If you give a[0]. compiler will make it to *(a+0).

So you are giving the 0[a]. It will make that as *(0+a). So it is working.

Karthikeyan.R.S
  • 3,991
  • 1
  • 19
  • 31