[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Please don't do this (code fragment)



Richard Kettlewell wrote:

> Even if you don't care about weird platforms, "x > -1" is a
> ridiculously obscure test in this context; to achieve the same effect
> it would be much clearer to make x unsigned and do "x <=
> (unsigned)INT_MAX".

I find "x <= (unsigned) INT_MAX" to be more obscure than the original.
When I first glanced at it, I thought, "That's dumb, x is ALWAYS less
than or equal to INT_MAX by definition!" Then my second thought was that
the cast on the constant will cause x to also be converted to unsigned.
In contrast, when I saw "x > -1", I immediately realized it was testing
for wraparound.

To achieve almost the same effect (probably close enough in this
situation), it would be better to simply test for "x < INT_MAX" -- it's
clearer than either the original or your cast-dependent version, and
only stops one iteration sooner. Since in this case the actual number of
iterations was not the point (rather, merely that the loop should be
guaranteed to terminate eventually), it ought to be sufficient.

In any case, trying to find the best way to express a really bad idea is
futile.

Craig

Attachment: pgpEkoM1VFgHz.pgp
Description: PGP signature


Reply to: