bearophile can say "i told you so" (re uint->int implicit conv)

Steven Schveighoffer schveiguy at yahoo.com
Thu Apr 4 12:21:36 PDT 2013


On Thu, 04 Apr 2013 15:10:28 -0400, Walter Bright  
<newshound2 at digitalmars.com> wrote:

> On 4/2/2013 8:10 PM, Steven Schveighoffer wrote:
>> On Tue, 02 Apr 2013 16:32:21 -0400, Walter Bright  
>> <newshound2 at digitalmars.com>
>> wrote:
>>> For example, with a signed array index, a bounds check is two  
>>> comparisons
>>> rather than one.
>>
>> Why?
>>
>> struct myArr
>> {
>>     int length;
>>     int opIndex(int idx) { if(cast(uint)idx >= cast(uint)length) throw  
>> new
>> RangeError(); ...}
>> }
>
> Being able to cast to unsigned implies that the unsigned types exist. So  
> no improvement.

The issue is the type of length, not that uints exist.  In fact, opIndex  
can take a uint, and then you don't need any casts, as far as I know:

int opIndex(uint idx) { if(idx >= length) throw new RangeError(); ...}

I think length will be promoted to uint (and it is always positive), so  
it's fine, only requires one check.

-Steve


More information about the Digitalmars-d mailing list