Signed word lengths and indexes

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Tue Jun 15 07:12:50 PDT 2010


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.
    }


> Notice why clever tricks are bad? They generate meaningless discussions
> :)

I don't think the discussion is meaningless.  I learned a new trick (or a 
new abomination, depending on your viewpoint), that I'll keep in mind 
next time I write a similar loop. ;)

-Lars


More information about the Digitalmars-d mailing list