4 ms·
>, subscripts are just adding to pointers, and since addition is commutative, then so is the subscript operator. [...] A lot to unpack from such little code, an
by jasode 10y ago
>, subscripts are just adding to pointers, and since addition is commutative, then so is the subscript operator. [...]
A lot to unpack from such little code, and plenty to learn.
It was over 25 years ago that I first came across the C language FAQ from the Usenet group comp.lang.c and it explained the "commutative property" of array subscripts. (Online version here: http://c-faq.com/aryptr/joke.html http://c-faq.com/aryptr/joke.html).
Another similar stackoverflow Q&A has also been done: http://stackoverflow.com/questions/381542/with-c-arrays-why-is-it-the-case-that-a5-5a http://stackoverflow.com/questions/381542/with-c-arrays-why-...
Over the last 2 decades, I have never needed the knowledge that the C language lets you put a number outside the brackets instead of inside it. Other than deciphering obfuscated C puzzles, I've never run across any real world source code that took advantage of that syntactic quirk. So yes, I did learn that trivia about array subscripts -- but it was useless knowledge.
- bodyfour 10y agoThe only time I've found it useful is making macros that expect an array a little safer in C++. For example: #define count(array) (sizeof(array) / sizeof(0[array])) ...will conveniently cause a compile error if you accidentally pass in a std::vector instead of an array.
- jasode 10y agoThanks for the heads up. Not suprisingly, a related stackoverflow q&a mentions that macro and also another more convoluted one from Chromium that protects against accidental pointers being passed: http://stackoverflow.com/a/1598827 http://stackoverflow.com/a/1598827
- nicky0 10y agoI have been C programming on and off for 20 years, and thought I know every trick. But no.
- beeforpork 10y ago20 years it is for me, too. And the exact rules of integer constants and their exact type have puzzled me lately. So I was not surprised to find more tricks for countof() here, to make it more safe to use. Nice! Also, typechecking macro arguments with ?: is quite interesting, check it out. :-)
- adamnemecek 10y ago> but it was useless knowledge. welcome to C programming!