Error on negating unsigned types

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Thu Jul 13 04:48:02 PDT 2017


On 7/12/17 5:24 PM, Johan Engelen wrote:
> On Wednesday, 12 July 2017 at 20:12:03 UTC, Steven Schveighoffer wrote:
>> ...
>> Which means this may cause a bunch of nuisance errors.
> 
> It's a trade-off between nuisance in some cases (the Phobos ones can be 
> solved with val = abs(val), or with static if), and possibly catching 
> bugs in other cases.
> 
> We can compare this with negation of a bool and subtracting a bool:
> ```
> bool b;
> auto x = 1 - b; // allowed
> auto y = -b; // not allowed
> ```
> 

My only point is with Andrei's assertion that it "exposed two bugs in 
Phobos".

In terms of the trade-off, it looks like this is just a straight bug 
that should be fixed. If the behavior goes back to being like C, is it 
still so bad that it needs an error?

My testing:

import std.stdio;
void main()
{
     ubyte x = 5;
     int y = -x;
     writeln(y);
     uint t = 0;
     t += x;
     writeln(t);
     t += y;
     writeln(t);
}

outputs:
251
5
256

In C:

#include <stdio.h>
int main()
{
     unsigned char x = 5;
     int y = -x;
     printf("%d\n", y);
     unsigned int t = 0;
     t += x;
     printf("%u\n", t);
     t += y;
     printf("%u\n", t);
     return 0;
}

outputs:
-5
5
0

The C behavior seems fine to me.

-Steve


More information about the Digitalmars-d mailing list