In comp.lang.c++ Lynn McGuire <
lynnmc...@gmail.com> wrote:
> ???Why do arrays start at 0?"
>
https://buttondown.email/hillelwayne/archive/why-do-arrays-start-at-0/
>
> "It's not the reason you think. No, it's not that reason either.???
>
> My Fortran starts at one. My C++ starts at zero. This has made my life
> hell.
I don't know if it's the *original* reason, but I would assume that at least
in C one of the main reasons is the principle of maximum efficiency.
In many processor architectures the concept of "array" exists, at least
when it comes to values of the register sizes (ie. usually 1-byte,
2-byte, 4-byte and 8-byte elements, the last one at least on 64-bit
architectures). Prominently the concept of an indexable array exists
in the x86 architecture. (I don't remember now if it also exists in
the ARM architecture, but I would guess so.)
Generally when a processor architecture supports the concept of an "array",
it does so by having instructions that take (at least) two registers as
the input or the output parameter: A base address, and an offset. The
memory location of the element is calculated by adding those two. (The
number of bytes that an offset of 1 jumps depends on the instruction,
and thus multi-byte elements are supported.)
Thus zero-indexing is extraordinarily natural in processor architectures:
The "index" is actually an offset. It's a value you add to the base
address in order to get to the location you want. Thus, the first element
is at index/offset 0.
Since that's the case, the most optimal way to handle low-level arrays is
to have 0-based indexing in the programming language as well. That way
you don't need to be subtracting 1 from the index every time an array is
accessed (or you don't need an extraneous unused element at the beginning
of the array, consuming memory for no reason).
Also, since C supports pointer arithmetic, many operations become simpler.
Such as getting the index of an element when what you have is a pointer to
it (and the pointer to the start of the array).