Signed word lengths and indexes

Steven Schveighoffer schveiguy at yahoo.com
Tue Jun 15 07:20:35 PDT 2010


On Tue, 15 Jun 2010 08:49:56 -0400, Pelle <pelle.mansson at gmail.com> wrote:

> On 06/15/2010 02:10 PM, Steven Schveighoffer wrote:
>> 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.
>
> Clever code is bad because you have to think a couple of times more  
> every time you see it.

This is a temporary problem.  Once you get used to any particular coding  
trick, you understand it better.

> Also, it looks wrong.

Why?  i is unsigned, therefore >= 0, and must be < length.  That seems  
reasonable and correct to me.

>
>> In this particular instance, the code is both clear and concise.
>>
>> 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)
>>
>> The compiler will throw away the second check during optimization,
>> because i is always >= 0. I don't see why such code should be preferred.
>>
>> -Steve
>
> This will probably generate similar code:
>
> for (uint i = end - 1; i < uint.max; --i)
>
> Same functionality, really clever.

What if end > length?

This is no more clever than the original, but allows bugs.  It's not  
clever, it's wrong.  In addition, it's purposefully obfuscated, while the  
original code is quite clear.  I can obfuscate even further, but I don't  
see why you would want such a thing:

for(uint i = end - 1; i < -1; --i)

"There's a fine line between clever and stupid" --Nigel Tufnel, This is  
Spinal Tap

-Steve


More information about the Digitalmars-d mailing list