abs and minimum values

Siarhei Siamashka siarhei.siamashka at gmail.com
Sun Oct 31 10:12:49 UTC 2021


On Sunday, 31 October 2021 at 05:04:33 UTC, Dom DiSc wrote:
> 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.

Then let's change the example to:

    int b = -4;
    writeln(-abs(b));

What would one normally expect to be printed here? Should the 
unary minus operator also do some kind of implicit "unsigned -> 
signed" type change magic to accommodate this modified version of 
the abs function and make it behave in a non-surprising way?


More information about the Digitalmars-d-learn mailing list