Signed word lengths and indexes

Pelle pelle.mansson at gmail.com
Tue Jun 15 07:35:41 PDT 2010


On 06/15/2010 04:12 PM, Lars T. Kyllingstad wrote:
> On Tue, 15 Jun 2010 16:05:08 +0200, Pelle wrote:
>
>> On 06/15/2010 03:25 PM, Adam Ruppe wrote:
>>> On 6/15/10, Pelle<pelle.mansson at gmail.com>   wrote:
>>>> for (uint i = end - 1; i<   uint.max; --i)
>>>>
>>>> Same functionality, really clever.
>>>
>>> That's wrong rather than clever though.
>>>
>>> for(i<   length) is saying "continue as long as you are inside the
>>> array's bounds", which is exactly what you mean in that loop. The only
>>> "tricky" is the understanding that an array index is never negative,
>>> but this shouldn't require extra thought in the first place.
>>
>> Using the length is meaningless, any uint>= length will work just as
>> well. Using the length there is meaningless, since that's really not
>> what you compare against.
>
> As long as you only decrease by one, your trick will work just as well.
> In a more general case, it won't:
>
>      for (uint i=end-1; i<uint.max; i--)
>      {
>          if (badTiming) i--;
>          // Oops, we may just have set i = uint.max - 1.
>      }

The same can be said if you use length, and length happens to be big. 
You really should use continue in this case.


More information about the Digitalmars-d mailing list