4 ms·
Arrays start at 0 because they're really just pointers. "[x]" is just shorthand for "+ x * sizeof". The first element is the one stored at the pointer address
by codefreeordie 4y ago
Arrays start at 0 because they're really just pointers. "[x]" is just shorthand for "+ x * sizeof". The first element is the one stored at the pointer address (0 sizeofs ahead of the pointer, the next element is stored 1 sizeof ahead of the pointer, etc.
- nicoburns 4y agoThat's just convention though. There's no reason "[x]" couldn't have been defined to be "+ (x - 1) * sizeof". There would be no runtime cost to this, and the compile time penalty would be tiny even on ancient systems.
- nwlieb 4y agoIs `(x - 1)` not a runtime cost if `x` is a runtime variable?
- vikingerik 4y agoNot on many instruction architectures - addressing modes often support adding/subtracting a constant.
- giraffe_lady 4y agoThat answers something like "what are the technical benefits to zero-based arrays" but not "why are zero-based arrays such a strong convention in programming languages." For that you'd have to read the article I guess.
- JKCalhoun 4y agoOr it could be: "technical benefits to zero-based arrays" -> "why zero-based arrays are a strong convention" Article mentions that Hoye says as much but is dismissive of it. I am not sure why he would be so quick to dismiss.
- vidarh 4y agoIn C, "a[x]" is effectively syntactic sugar for just "*(a+x)" (conversion rules for "+" means you don't need the sizeof). It also means you can reverse it and write e.g. "5[somearray]" if you really want to make developers want to throw rocks at you.
- yonrg 4y agohehe, that was me :) when I was young.