3

I've read this and don't believe it :) I've no compiler here to test.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Juanjo Conti
  • 28,823
  • 42
  • 111
  • 133

3 Answers3

9

In raw C, the [] notation is just a pointer math helper. Before [], you'd look for the fourth char in the block pointed to by ptr like:

*(ptr+4)

Then, they introduced a shortcut which looked better:

ptr[4]

Which transaltes to the earlier expression. But, if you'd write it like:

4[ptr]

This would translate to:

*(4+ptr)

Which is indeed the same thing.

Andomar
  • 232,371
  • 49
  • 380
  • 404
5

Because a[b] is exactly the same as *(a+b), and + is commutatitve.

chars[4] is *(chars+4), and 4[chars] is *(4+chars)

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
4

http://c-faq.com/aryptr/joke.html Try this to test compile: http://codepad.org/

micmoo
  • 5,991
  • 3
  • 22
  • 16