3

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

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
Juanjo Conti
  • 27,061
  • 38
  • 104
  • 130

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
  • 225,110
  • 44
  • 364
  • 390
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
  • 345,440
  • 70
  • 544
  • 649
4

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

micmoo
  • 5,941
  • 3
  • 20
  • 16