Array start index

Rikki Cattermole via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 1 02:42:35 PDT 2015


On 1/08/2015 9:35 p.m., DLearner wrote:
> Does the D language set in stone that the first element of an array
> _has_ to be index zero?
> Wouldn't starting array elements at one avoid the common 'off-by-one'
> logic error, it does
> seem more natural to begin a count at 1.
>
> Actually, maybe even better to allow array definitions of form
> int foo[x:y];
> (y >= x) creating integer variables foo[x], foo[x+1],...,foo[y].
>
> I think the (very old) IBM PL/I language was like this.

In c style languages (like D) the index actually defines the offset in 
memory. Not actually the index.
So while in some languages 1 is used instead of 0, 0 maps better to the 
hardware.

Think of this byte array:

ubyte* myptr = [

|---|-------|
| i | value |
|---|-------|
| 0 | 1     |
| 1 | 255   |

];

For 0 start of index:
size_t i = 0;
assert(myptr[i] == 1);

For 1 start of index:
size_t i = 1;
assert(i != 0);
assert(myptr[i-1] == 1);

While this is not the complete reason why 0 is chosen, it is something 
to think about.


More information about the Digitalmars-d-learn mailing list