Array start index

DLearner via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 1 11:47:06 PDT 2015


On Saturday, 1 August 2015 at 17:55:06 UTC, John Colvin wrote:
> On Saturday, 1 August 2015 at 09:35:53 UTC, DLearner wrote:
>> Does the D language set in stone that the first element of an 
>> array _has_ to be index zero?
>
> For the builtin slice types? Yes, set in stone.
>
>> 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.
>
> See 
> https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html
>
> As other commenters have/will point out, you can easily define 
> a custom type in D that behaves as you describe, and - Dijkstra 
> notwithstanding - there are valid uses for such things.

D is a C derivative, so it seems a shame not to identify causes 
of bugs in C,
and design them out in D.

For example, in C difficult to write non-trivial commercial 
programs without using pointers.
Pointer manipulation has a terrible reputation for bugs.
But in D, easy to write commercial programs without using 
pointers.
Problem has been designed away.

Similarly, off-by-one array bugs are commonplace in C.
We should seek to eliminate the source of those bugs, which 
basically reduces to the
issue that programmers find it unnatural to start a count at zero.
Whether they _should_ find a zero start unnatural is irrelevant - 
they just do as an
observed fact, so let's change the language so the issue is 
avoided (designed away).

Suggestion: if the codebase for D is considered so large that 
zero-basing cannot now be changed,
why not extend the language to allow for array definitions like 
'int[x:y] foo'?
And then have a rule that 'int[:y] bar' defines a 1-based array 
of y elements?


More information about the Digitalmars-d-learn mailing list