3 ms·
A slight tangent, but something that surprised me: The [] operator literally is just syntactic sugar for pointer dereferencing and addition, so that the followi
by pmjordan 17y ago
A slight tangent, but something that surprised me: The [] operator literally is just syntactic sugar for pointer dereferencing and addition, so that the following equivalence holds:
a[b] == *(a + b);
The surprising consequence of this is that the following is legal:
int foo[] = { 1, 2, 3 };
int bar = 2[foo]; /* yes, this evaluates to 3 */
because
*(2 + foo)
is legal, and + is commutative. This works for both pointers and arrays. I haven't worked out a practical use, though I suspect the C++ metaprogramming crowd might have. Obviously the equivalence only holds on the native types in C++ as [], + and * can each be separately overloaded.
- jws 17y agoI apologize for initially considering you a crank, but gcc 4.2.1 agrees with you.
- pmjordan 17y agoI'm like 99.9% sure it's in the standard. gcc -pedantic -ansi certainly doesn't complain.
- JeremyStein 17y agoNo practical use?! Why, it's practically a requirement for IOCCC entries. :)
- mark_h 17y agoIn fact, I recently only realised this myself this courtesy of this article (a tutorial on writing obfuscated C :)): http://www.dreamincode.net/forums/index.php?showtopic=38102 http://www.dreamincode.net/forums/index.php?showtopic=38102 It makes perfect sense when you consider the semantics of [], but I never would have thought to try it myself!
- grogers 17y agoThe only problem is that in C++, overloading operator[] has to be a non-static member function. x[y] is treated as x.operator[](y) if x is of class type. So x[y] may not be the same as y[x] if they are class types. So maybe that has some useful property, but it isn't really the same.
- mfukar 17y agoC is not C++, though.
- NathanKP 17y agoThat is unbelievable! I never would have thought to try 2[foo] even though I knew that it was essentially just *(a+b).