abs and minimum values

Ali Çehreli acehreli at yahoo.com
Fri Oct 29 14:20:09 UTC 2021


On 10/29/21 1:05 AM, Dom DiSc wrote:

 > I recommend to implement your own abs function this way (was not
 > accepted for phobos, as it now does NOT return the same type as the
 > argument, which was considered a "breaking change" :-( ):

Combined with automatic type conversions we got from C, it can cause 
unexpected results as well. One might expect the following program to 
print -1 when that definition of abs() is used in an expression:

import std.traits;
import std.stdio;

/// get the absolute value of x as unsigned type. always succeeds, even 
for T.min
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.

Ali



More information about the Digitalmars-d-learn mailing list