Array start index

via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Aug 4 01:18:49 PDT 2015


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?
> 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.

I, too, don't think this is a good idea in general, but I can see 
a few use-cases where 1-based indices may be more natural. It's 
easy to define a wrapper:

     struct OneBasedArray(T) {
         T[] _payload;

         alias _payload this;

         T opIndex(size_t index) {
             assert(index > 0);
             return _payload[index-1];
         }

         void opIndexAssign(U : T)(size_t index, auto ref U value) 
{
             assert(index > 0);
             _payload[index-1] = value;
         }
     }

     unittest {
         OneBasedArray!int arr;
         arr = [1,2,3];
         arr ~= 4;
         assert(arr.length == 4);
         assert(arr[1] == 1);
         assert(arr[2] == 2);
         assert(arr[3] == 3);
         assert(arr[4] == 4);
     }

Test with:

     rdmd -main -unittest xx.d

This can of course be easily extended to support other bases than 
one.


More information about the Digitalmars-d-learn mailing list