On 2018-07-19 14:41:34 +0100, Davin McCall wrote:
> I agree completely but, and sorry if I'm missing something, the labs()
> function could still be required to return LONG_MIN if passed LONG_MIN,
> correct? It's just that the implementation changes from:
> 
>    long labs(long i)
>    {
>         return (i > 0) ? i : -i;
>    }
> 
> 
> to, for example:
> 
>    long labs(long i)
>    {
>         if (i == LONG_MIN) return LONG_MIN;
>         return (i > 0) ? i : -i;
>    }
> 
> 
> (which is potentially compiled to the same thing, though a brief test shows
> current compilers fail to do that).
> 
> So, this POSIX requirement doesn't actually impose any extra requirements on
> the C compiler, if I understand correctly - just on the implementation of
> the abs() functions.

The problem with the new POSIX requirement is not just the
implementation of the function, but

1. The programs will have less chance to be optimized. With ISO C's
   specification and without an knowledge on i, the compiler can
   assume that the result of labs(i) is in the range 0 .. LONG_MAX.
   But with the new POSIX requirement, the range of this result
   becomes LONG_MIN .. LONG_MAX.

2. For security-sensitive programs and for testing, UBsan would
   no longer be able to fail on labs(LONG_MIN).

3. The divergence between ISO C and POSIX could yield obscure failures
   when a program is not compiled in the mode it should be.

And labs(LONG_MIN) -> LONG_MIN would not bring something really useful
for the user. And this cannot even be regarded as a simplification if
the user wants to put the result in an unsigned type, because he would
still need to be very careful. For instance,

  unsigned long long a = labs(i);

will probably not give what the user expects on i = LONG_MIN.

-- 
Vincent Lefèvre <vinc...@vinc17.net> - Web: <https://www.vinc17.net/>
100% accessible validated (X)HTML - Blog: <https://www.vinc17.net/blog/>
Work: CR INRIA - computer arithmetic / AriC project (LIP, ENS-Lyon)

Reply via email to