disabling unary "-" for unsigned types

Steven Schveighoffer schveiguy at yahoo.com
Wed Feb 17 09:16:37 PST 2010


Don Wrote:

> Steven Schveighoffer wrote:
> > Any opposing view would have to include what obtaining the unsigned negation of an unsigned value is useful for.  And literals don't count because they're easily expressed otherwise :)
> 
> x & -x
> Nonzero if x has has more than one bit set, ie is not a perfect power of 
> 2. I use that often.

Fine, this would not be disallowed in my mind.  The abuse is not simply applying negation to an unsigned, it is then using the result as unsigned.

Incidentally, I always used the construct x & (x-1) to be zero if it's an exact power of 2.  It's not much different.

> My opinion: unsigned types get used *far* more often than they should. 
> If this kind of behaviour confuses you, there's no way you should be 
> using unsigned.
> Really, the problem is that people abuse unsigned to mean 'this is a 
> positive integer'. And of course, negation doesn't make sense in the 
> context of the naturals. But that is NOT what unsigned is. Unsigned 
> types are types with NO SIGN.

If unsigned types get used far more often than they should, then they shouldn't be all over the place in the standard language (i.e. size_t is used for everything size related).  You simply can't avoid using unsigned.  It's also useful for when you don't think you should ever receive inputs that are negative.

That being said, this one issue of applying negation and then using the result as an unsigned is not a very common usage, and is always an error.  I don't see the harm in disallowing it.

-Steve



More information about the Digitalmars-d mailing list