Signed word lengths and indexes

Steven Schveighoffer schveiguy at yahoo.com
Tue Jun 15 07:27:21 PDT 2010


On Tue, 15 Jun 2010 10:08:38 -0400, BCS <none at anon.com> wrote:

> Hello Steven,
>
>> On Mon, 14 Jun 2010 21:48:10 -0400, BCS <none at anon.com> wrote:
>>
>>> Hello Steven,
>>>
>>>> div0 <div0 at users.sourceforge.net> writes:
>>>>
>>>>> for(uint i = end - 1; i < length; --i)
>>>>> ...
>>>> What does "length" represent here? It's not clear to me how "i"
>>>> descending toward zero is going to break the guard condition.
>>>>
>>> My thought exactly.
>>>  If i<j and you --i, I'd assume i<j, if your code depends on the case
>>> where the assumption is wrong, don't ask me to do a code review
>>> because  I won't sign off on it.
>>>
>> i is unsigned, and therefore can never be less than 0.  It's actually
>> a  clever way to do it that I've never thought of.
>
> It's /to/ clever. That's the problem. If you haven't seen it in a while,  
> it's confusing and it LOOKS wrong even if you have.

This is easily solved - put in a comment.  I frequently put comments in my  
code because I know I'm going to forget why I did something.

>
>>  Read it more like this:
>>  for(uint i = end - 1; i < length && i >= 0; --i)
>>  But the i >= 0 is implicit because i is unsigned.
>>
>
> I know, that's exactly "the case where the assumption is wrong".
>

Reading code assuming integer wrapping never occurs is a big mistake.  You  
should learn to assume wrapping is always possible.

-Steve


More information about the Digitalmars-d mailing list