r/ProgrammerTIL • u/Srimshady • Sep 14 '17
Other [c++] Array declarations are commutative/invertible.
array[4] is equivalent to 4[array]. Not that you would ever really use it.
43
Upvotes
r/ProgrammerTIL • u/Srimshady • Sep 14 '17
array[4] is equivalent to 4[array]. Not that you would ever really use it.
3
u/Avander Sep 14 '17
Same for access.
18
u/JH4mmer Sep 14 '17
I usually show this to my beginning programming students when we're covering pointers and their relationship to arrays. x[i] is just a shorthand for *(x + i) for simple pointers (which is also why arrays start at 0). Addition of integers is communative. Therefore, *(x + i) == *(i + x) == i[x]. This will work as long as your compiler uses that particular transformation in the implementation of the array access operator. I'm not sure if it's guaranteed by the standard, but most compilers I've seen do implement it this way.
It's a fun trick to play, but I would hesitate to apply it in any sort of practical setting. Clarity is important. :-)
7
u/_guy_fawkes Sep 14 '17
sounds like an http://ioccc.org trick
1
u/[deleted] Sep 14 '17
Array subscript is syntactic sugar for pointer arithmetic.