Signed word lengths and indexes

Steven Schveighoffer schveiguy at yahoo.com
Tue Jun 15 08:06:04 PDT 2010


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

> Hello Steven,
>
>> On Tue, 15 Jun 2010 07:30:52 -0400, bearophile
>> <bearophileHUGS at lycos.com>  wrote:
>>
>>> Steven Schveighoffer:
>>>
>>>> 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.
>>>>
>>> Clever code is bad. It must be minimized. In some rare situations it
>>> becomes useful, but its usage must be seen as a failure of the
>>> programmer, that was unable to write not-clever code that does the
>>> same  things.
>>>
>> Clever code is bad?  What are you smoking?  In my opinion, clever code
>> that is clear and concise should always be favored over code that is
>> unnecessarily verbose.
>
> Cleaver in my book normally equates to: requiters extra thought to  
> create and read. The exact opposite of clever is not dumb, but simple:  
> with very un-clever code the reader is I/O bound, they can understand as  
> fast as they can read it.

Clever code does not have to be hard to understand.  In this case, it's  
not hard to understand.  You admit yourself that you understood it within  
a second ;)

>>  In this particular instance, the code is both clear and concise.
>
> That code might be concise but it is not clear.

Since uint is declared inside the loop statement, I'd say it is clear --  
it's not open to misinterpretation.  If i was defined elsewhere, I'd agree.

>
>>  The following line of code should generate the exact same code, but is
>> more verbose:
>>  for(uint i = end - 1; i < length && i >= 0; --i)
>
> That code is just as bad IMO and for exactly the same reason: you are  
> counting on underflow and wrapping to make a i<j test start failing  
> after i decrease.

Well, I guess that's one way to look at it.  But what I like a lot about  
the original example, is there is no mixing of unsigned/signed types.  So  
you are always dealing with unsigned, so you do not have to deal with  
worrying about integer promotion.

Thinking about unsigned arithmetic is sometimes difficult, but if you  
understand the rules, using underflow to your advantage is fine IMO.

-Steve


More information about the Digitalmars-d mailing list