abs and minimum values
Siarhei Siamashka
siarhei.siamashka at gmail.com
Sun Oct 31 07:22:57 UTC 2021
On Thursday, 28 October 2021 at 21:23:15 UTC, kyle wrote:
> ```
> void main()
> {
> import std.math : abs, sgn;
>
> alias n_type = short; //or int, long, byte, whatever
>
> assert(n_type.min == abs(n_type.min));
> assert(sgn(abs(n_type.min)) == -1);
> }
> ```
> I stumbled into this fun today. I understand why abs yields a
> negative value here with overflow and no promotion. I just want
> to know if it should. Should abs ever return a negative number?
> Thanks.
I think that the best way to deal with this stuff without losing
sanity is to introduce a special constant "n_type.nan" for signed
integer data types. Then you get "abs(n_type.nan) == n_type.nan",
which makes more sense.
All the uses of "n_type.min" in your code can be replaced either
with "n_type.nan" or "-n_type.max", depending on the context and
your intention. The existing constant "n_type.min" can be
deprecated for signed integer types. Compilers and static
analysis tools could warn about its use.
More information about the Digitalmars-d-learn
mailing list