Skip to main content
GameDev.net gamedev.net
🔒 Locked

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

Started by xstreme2000 Nov 21, 2006 at 8:04 AM 2 replies 1.3k views
Original Post
xstreme2000
xstreme2000
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
Rattrap
Rattrap
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]
jpetrie
jpetrie
x[y] is the same as *(x + y). The former is, in fact, just syntactic sugar for the latter.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.