Why do arrays start at 0?
buttondown.email
Why do arrays start at 0?
1–10 of 702 posts
Re: Why do arrays start at 0?
#2Re: Why do arrays start at 0?
#3Re: Why do arrays start at 0?
#4Re: Why do arrays start at 0?
#5Arrays 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?
#6I have always assumed that is just one less operation required to resolve the absolute memory address.
1. Optimizing compilers exist.
2. Addressing at fixed offsets is cheap (a single instruction): https://en.wikipedia.org/wiki/Addressing_mode
0-based indexing is superior (as a default) because it simplifies a lot of common math, as discussed in TFA.
Re: Why do arrays start at 0?
#7Re: Why do arrays start at 0?
#8I feel like I've also seen algorithms that work out better with 1 based indices, but not as many.
Re: Why do arrays start at 0?
#9I have always assumed that is just one less operation required to resolve the absolute memory address.
I'd be surprised if the use of zero vs one actually made any difference, from a number of operations point of view -- from the compiler's point of view, the first element in the array is the first element in the array, no matter what we call it.
I mean in an extreme edge case maybe if you are computing an index, and it happens to be zero, then in your math maybe some identity related to zero could be exploited (go to element simple_integer*complicated_function(), where simple_number might be zero) but that seems a bit silly.
Re: Why do arrays start at 0?
#10I have always assumed that is just one less operation required to resolve the absolute memory address.