Negative index range violation

Timon Gehr timon.gehr at gmx.ch
Thu Feb 22 15:26:40 UTC 2018


On 22.02.2018 01:26, Adam D. Ruppe wrote:
> On Thursday, 22 February 2018 at 00:13:43 UTC, SrMordred wrote:
>> string x = "123";
>> auto c = x.ptr;
>> c++;
>> writeln(c[-1]); // 1
> 
> That's only happening because pointers bypass range checks.
> 
>> writeln(c[-1..0]); //BOOM Range violation
> 
> But with a slice negative indexes are never allowed, even on a pointer.

Actually, it's slightly more complicated than that. E.g. c[-2..-1] does 
not trigger the range check and will behave as expected. For slices 
c[l..r] there is a check whether cast(size_t)l<=cast(size_t)r. The range 
violation happens because -1 is larger than 0 as an unsigned integer.


More information about the Digitalmars-d-learn mailing list