Array start index

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Aug 3 19:02:17 PDT 2015


On Monday, August 03, 2015 21:32:03 DLearner via Digitalmars-d-learn wrote:
> On Monday, 3 August 2015 at 13:45:01 UTC, bachmeier wrote:
> > On Sunday, 2 August 2015 at 21:58:48 UTC, QAston wrote:
> >
> >> Adding 1-indexed arrays to the language fixes nothing. Just
> >> write your 1-indexed array type and if you enjoy using it,
> >> publish it as a library. Who knows, if demand is high it may
> >> even end up in phobos.
> >
> > Oh, I don't think that's a good idea. It's too confusing to
> > have more than one method of indexing within the same language.
> > You just have to do a thorough job of testing, as the
> > possibility of errors is something you'll have to live with,
> > given the different design choices of different languages.
>
> Looks like 0-base is fixed, to avoid problems with existing code.
>
> But nothing stops _adding_ to the language by allowing
> int[x:y] foo to mean valid symbols are foo[x], foo[x+1],...,
> foo[y].
> Plus rule that int[:y] means valid symbols are foo[1],
> foo[2],..., foo[y].
>
> That way, 1-start achieved, with no conflict with existing code?

Almost all programming languages in heavy use at this point in time start
indexing at 0. It would be highly confusing to almost all programmers out
there to have 1-based indexing. In addition, having 0-based indexing
actually makes checking against the end of arrays and other random-access
ranges easier. You can just check against length without having to do any
math. In general, I would expect 1-based indexing to _increase_ the number
of off by one errors in code - both because 0-based indexing helps avoid
such problems when dealing with the end of the array and more importantly,
because almost everyone expects 0-based indexing.

You're really barking up the wrong tree if you're trying to get any support
for 1-based indexing in D. I doubt that you will see much of anyone who
thinks that it's even vaguely a good idea, and there's no way that Walter or
Andrei (or probably anyone in the main dev team) who is going to agree that
it's even worth considering.

I think that the reality of the matter is that if you're going to do much
programming - especially if you're going to be professional programmer - you
just need to get used to the idea that array indices start at 0. There are a
few languages out there where they don't, but they are far from the norm.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list