Range violation instead of empty slice on a[3 .. 2]

BBaz via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 21 10:28:49 PST 2015


On Saturday, 21 November 2015 at 18:03:07 UTC, SimonN wrote:
>     string a = "hello";
>     string b = a[3 .. 2];
>
> I expect b to become an empty slice, because 3 is >= 2 already 
> after 0 increments, making the slice length 0. Instead, the 
> code throws a range violation.
>
> Expressions of this kind come up, e.g., when taking slices near 
> the end of arrays, like "slice = a[b.length .. $];". To make 
> this robust, I need an extra check for b.length > a.length, 
> returning null in this case, otherwise a[b.length .. $].
>
> What's the design reason to prefer throwing over returning an 
> empty slice?
>
> -- Simon

this is only an error if bounds checking is not turned on. If you 
compile your example with DMD option "-boundscheck=off", nothing 
happens, and the slice will be equal (here) to a[3..$];


More information about the Digitalmars-d-learn mailing list