News for hackers. Stuff that matters.
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.
Re:Why do arrays start at 0? by vidarh on Wednesday August 24, 2022 @01:05PM (#32582437)
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.
Re:Why do arrays start at 0? by yonrg on Wednesday August 24, 2022 @05:29PM (#32586027)
hehe, that was me :) when I was young.
Re:Why do arrays start at 0? by nicoburns on Wednesday August 24, 2022 @01:06PM (#32582455)
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.
Re:Why do arrays start at 0? by nwlieb on Wednesday August 24, 2022 @01:29PM (#32582780)
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.
Re:Why do arrays start at 0? by JKCalhoun on Wednesday August 24, 2022 @01:00PM (#32582346)
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.