Micro-GMP

Vincent Lefevre vincent at vinc17.net
Mon Dec 3 12:43:51 UTC 2018


On 2018-12-03 13:04:11 +0100, Torbjorn Granlund wrote:
>   > What is the purpose of GMP_NEG_CAST
>   >
>   > #define GMP_NEG_CAST(T,x) (-((T)((x) + 1) - 1))
>   >
>   > instead of just a cast followed by a negation? i.e.
>   >
>   >  mpz_set_ui (r, - (unsigned long int) x);
> 
> This is confusing.
> 
> 1. We can never use this for signed types with negative values if T is
>    unsigned.
> 
> 2. For signed source types, the + 1 - 1 trickery might help for MIN_INT
>    (etc) but will cause undefined behavious for MAX_INT (etc).

If I understand correctly, this macro is designed to be applied on
negative values with T being the unsigned integer type associated
with the type of x. In such a case, the + 1 - 1 trickery is harmless,
but also useless, even on the minimum negative value (if there is an
bug with some compiler, there is also a potential issue with all
negative values...).

BTW, with one's complement and sign-magnitude integer representations,
I assume that the most complex case for a compiler is the cast of 0
(which might be a negative zero) to unsigned, so that the compiler
must be very careful to change the representation of 0 in this case.
If x is negative, then with "- (unsigned long int) x", this problem
cannot occur. But on the contrary, this problem can occur with the
GMP_NEG_CAST macro, if x is -1 (in the case the compiler doesn't
optimize the + 1 - 1 trick to nothing).

-- 
Vincent Lefèvre <vincent at 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)


More information about the gmp-devel mailing list