abs and minimum values

Dom DiSc dominikus at scherkl.de
Sun Oct 31 05:04:33 UTC 2021

On Friday, 29 October 2021 at 14:20:09 UTC, Ali Çehreli wrote:
> Unsigned!T abs(T)(const(T) x) if(isIntegral!T)
> {
>    static if(isSigned!T) if(x < 0) return cast(Unsigned!T)-x;
>    return x;
> }
> void main() {
>   int a = -5;
>   int b = -4;
>   writeln(a + abs(b)); // -5 + 4 == -1? (No!)
> }
> The program prints uint.max.

This should be no surprise. You need to know what the resulting 
type of int + uint should be. And it is ...... uint!  which is 
one of the stupit integer-promotion rules inherited from C. I 
just don't understand how "promoting" something by dropping some 
important information (the sign) and on the fly also destroying 
the absolute value can ever be a good choice. I always thought it 
should be the other way round.
The way it is is like "promoting" int + float to int (by 
discarding the fraction part and possibly too high exponents). 
And those two types are also of same size, so this is not an 
Promotion should always be in a direction where it at least 
sometimes can be correct.

More information about the Digitalmars-d-learn mailing list