Error on negating unsigned types

Johan Engelen via Digitalmars-d digitalmars-d at puremagic.com
Tue Jul 11 13:05:43 PDT 2017


On Tuesday, 11 July 2017 at 20:02:07 UTC, Johan Engelen wrote:
> On Tuesday, 11 July 2017 at 19:57:06 UTC, Johan Engelen wrote:
>> On Tuesday, 11 July 2017 at 19:46:00 UTC, Johan Engelen wrote:
>>> The Weka folks would like to see a compile error on negating 
>>> unsigned types:
>>
>> Also this nice hackery would need a workaround:
>> ```
>>    if ((y&(-y))==y)
>> ```
>
> http://www.exploringbinary.com/ten-ways-to-check-if-an-integer-is-a-power-of-two-in-c/
>
> "The two’s complement of x is computed with ~x + 1, which 
> inverts the bits of x and adds 1 (~x + 1 is equivalent to -x, 
> but negation is technically illegal for an unsigned integer)."

Codegen is the same for both: https://godbolt.org/g/JiHiEe
So Phobos's `if ((y&(-y))==y)` can be rewritten to `if 
((y&(~y+1))==y)` without consequence.


More information about the Digitalmars-d mailing list