abs and minimum values
Ali Çehreli
acehreli at yahoo.com
Sun Oct 31 16:50:32 UTC 2021
On 10/30/21 10:04 PM, 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.
Yes, the programmer knew all that when they wrote that code when abs()
behaved the way it behaves today.
The code is an example of why abs() cannot be changed today to what you
propose. It would be a bad kind of breaking change: No compilation
error, no run-time error (if unlucky), and a weird bug 42 months from today.
Ali
More information about the Digitalmars-d-learn
mailing list