Re:Why do arrays start at 0?
by codefreeordie on Wednesday August 24, 2022 @12:42PM
(#32582041)
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.
[ Parent
| on HN ]
In 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.
hehe, that was me :) when I was young.
That'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.
Is `(x - 1)` not a runtime cost if `x` is a runtime variable?
Re:Why do arrays start at 0?
by vikingerik on Wednesday August 24, 2022 @02:57PM
(#32584103)
Not on many instruction architectures - addressing modes often support adding/subtracting a constant.
Re:Why do arrays start at 0?
by giraffe_lady on Wednesday August 24, 2022 @12:50PM
(#32582171)
That 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.
Or 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.