Array Lower Bounds

Bill Baxter dnewsgroup at billbaxter.com
Tue Dec 18 12:05:56 PST 2007


bearophile wrote:
> Mike Marquard:
>> I know the default starting index for arrays is zero in D. But is there any way you can change the lower bounds to something other zero? For instance having the index go from 1 to 10 or say 100 to 200.
> 
> Delphi, TurboPascal, and probably FreePascal have such feature, and once in a while it's useful, see here for example:
> http://blogs.warwick.ac.uk/mtcharemza/entry/fortran_9095_versus_1
> but it's not difficult to adapt your mind to the fixed 0 starting point, and you don't need to go looking at definition of the array type every time to see what's the actual starting point of the array you want to use.
> If you want to simulate something like that in C (and D) you may do something like the following, but I don't like this solution much, it's probably better to just use the 0 starting point (note that with -release the asserts go away, and -inline does its work, removing the call to bounds() too):
> 

I have wished on occasion that I could make a slice that started at its 
actual real index.  For instance when doing foreach on a slice:

foreach(i,v; things[p..$-q]) {
    // i counts from zero rather than p :-(
}

But as Daniel pointed out, that could be remedied by calling a separate 
function to get the delegate:

foreach(i,v; enumerate(things, p, things.length-q)) {
    // i from p to $-q here
}

It's too bad that writing a function like enumerate() makes my head hurt 
or I would undoubtedly use that kind of solution more often. :-)

--bb


More information about the Digitalmars-d-learn mailing list