[C++] Why is the predefined index operator commutative?

Started by
2 comments, last by xstreme2000 17 years, 4 months ago
I was looking at the page about the book C++ Gotchas by Stephen C. Dewhurst on Amazon when I noticed in one of the reviews someone states that this book talks about why the predefined index operator is commutative, e.g. referring to MyArray[24] is the same as referring to 24[MyArray]. Now I've not read the book so I don't know what the book say about it (I do intend to buy it & read it one day but not yet) but it's got me wandering, I've never seen that before and to refer to an element by index[array] seems backwards to me but I'm thinking there must be a good reason for this...does someone care to enlighten me? Many thanks, Tom
Advertisement
This is a little simplified, buts its basically the jist of it.

It's basically beacuse MyArray translates to an address location and the [] translates to adding its value to the address location to locate the element. If you look at it from that perspective (basically just addition) you get


x[y] == x + y

y[x] == x + y

and thus

x[y] == x + y == y[x]

x[y] == y[x]

"I can't believe I'm defending logic to a turing machine." - Kent Woolworth [Other Space]

x[y] is the same as *(x + y). The former is, in fact, just syntactic sugar for the latter.
That makes sense, thanks.

This topic is closed to new replies.

Advertisement