This is how you’re wrong, Mark. Freaking read the FAQ. The critical reason why it works is because of, as it says, “the pointer definition of array subscripting.” Commutativity of pointer arithmetic is of course relevant, but it’s by no means the primary reason why it works. Misunderstanding this, you made up something about how 5 is type cast to a char * (which by the way is illegal in ANSI C and will not compile) and how “abcdef” is type cast to int (not sure if it’s illegal but there’s a strong possibility it is). These are just details, but the point is, you got the details wrong because you fundamentally misunderstood the primary reason why it worked. And that is, because of the pointer definition of array subscripting. That’s the essence. The FAQ says it. Eric Mao got it. You didn’t. Hence, your reasoning is totally wrong.

Commutativity stems from that, it’s not the “reason”. It’s a side effect of the actual reason, which you didn’t mention at all. So, that’s why your reasoning is totally wrong. This should be clear.

Uh, for the non-nerds out there, this is about why 5[“abcdef”] works in C. The reason is (any other explanation is not the reason), array subscripting is immediately translated into pointer arithmetic. So if you have something like iarray[5], that’s immediately translated into something like *(iarray+5). K&R explicitly say so in their C book.

That’s why that expression works, because of the way C treats array subscripting. To say anything else misunderstands array subscripting and doesn’t explain why it works.

Leave a Reply

Your email address will not be published. Required fields are marked *