0

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
  • 42,835
  • 20
  • 145
  • 262
Chiru
  • 3,043
  • 1
  • 18
  • 28

3 Answers3

3

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
  • 130,437
  • 16
  • 177
  • 247
1

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
  • 19,653
  • 7
  • 38
  • 77
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,971
  • 1
  • 18
  • 31