Why does this work? Illogical array access

In simplistic terms, the access of an array element in C (and in C++, when [] isn’t overloaded) is as follows:

x[i] = *(x + i)

So, with this and a little bit of arithmetic…

  foo[i][bar]
= (foo[i])[bar]
= (*(foo + i))[bar]
= *((*(foo + i)) + bar)
= *(bar + (*(foo + i)))
= bar[*(foo + i)]
= bar[foo[i]]

Don’t use this “fact” though. As you’ve seen, it makes the code unreadable, and unreadable code is unmaintainable.

Leave a Comment