Negating a short?

Andy Valencia dont at spam.me
Wed Nov 6 01:03:25 UTC 2024


On Wednesday, 6 November 2024 at 00:00:48 UTC, Dennis wrote:

> That's right, it only removes the deprecation that requires a 
> double cast to fix, but you still need an explicit cast to 
> truncate the result of `-s` (which got promoted to `int`) back 
> to a `short`, unless the compiler can prove at compile time it 
> will always fit in 16 bits. This analysis is called Value Range 
> Propagation (VRP) in the specification: You can also use an 
> assignment operator, which allows overflow without explicit 
> cast:
>
> s *= -1;

Thank you!  *= it is, then.  I guess the oddity is actually that 
the negation of a long is a long, an int--int.  But short and 
byte -> int.  All of them have a value which won't fit in the 
type when negated.  I don't mind much, as I have no plans to do a 
lot of math on short.  But you may get visited by the 8- and 
16-bit Mafia at some point! :-)

Andy

     long l = -5;
     l = -l;
     writeln(l);

     int i = -5;
     i = -i;
     writeln(i);

     short s = -5;
     s = -s;
     writeln(s);

     byte b = -5;
     b = -b;
     writeln(b);



More information about the Digitalmars-d-learn mailing list