5

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

I am reading through a tutorial on C and I came across this syntax:

int doses[] = {1, 3, 2, 1000};
doses[3] == *(doses + 3) == *(3 + doses) == 3[doses]

Now the point is to get the int 1000, but the last one doesn't make any sense. Either its late and my brain is not functioning, its something specific to C, or its a typo. I want to cover all my basics when it comes to pointers so reading through it carefully. That means understanding it all. Any answers would be much appreciated!

Community
  • 1
  • 1
Andy
  • 10,553
  • 21
  • 75
  • 125

3 Answers3

7

From Wikipedia

Since the expression a[i] is semantically equivalent to *(a+i), which in turn is equivalent to *(i+a), the expression can also be written as i[a], although this form is rarely used.

Rotem
  • 21,452
  • 6
  • 62
  • 109
2

Yes, array subscripting is commutative in C. e1[e2] is indeed the same as *((e1)+(e2)). But it is useless in production code, and the only purpose of this notation is to make obfuscated source code.

md5
  • 23,373
  • 3
  • 44
  • 93
  • I'm curious if you know the reason as to why this decision was made in the design of array/pointer arithmetic? I agree it seems useless and not to mention confusing. But I guess now that I know it wouldn't be so bad. – Andy Dec 02 '12 at 09:47
  • @Andy: When C programming langage was designed, compilers didn't have enough memory to perform a lot of syntax check. So translating `E1[E2]` to `*((E1)+(E2))` reduced the cost of the compilation. – md5 Dec 02 '12 at 09:58
0
ISO c99 : 6.5.2.1 Array subscripting

1
One of the expressions shall have type ‘‘pointer to object type’’, the other expression shall have integer type, and the result has type ‘‘type’’.

E1[E2] either E1 will be pointer to object type and E2 will be integer type.

Or,

E1 is integer type and E2 is of pointer to that type

as + is commutative so E1[E2] == E2[E1] , because it's actually evaluated as (*(E1+E2))

Omkant
  • 9,018
  • 8
  • 39
  • 59