Type-generic macros for GMP with C11's _Generic keyword

Vincent Lefevre vincent at vinc17.net
Mon Jun 14 21:16:49 UTC 2021

On 2021-06-14 20:22:41 +0000, John Scott wrote:
> A naive implementation could look something like this for example:
> #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
> #define mpz_set(X, Y) _Generic((Y), \
> 	default: mpz_set, \
> 	unsigned long int: mpz_set_ui, \
> 	signed long int: mpz_set_si, \
> 	double: mpz_set_d, \
> 	const mpq_t: mpz_set_q, \
> 	const mpf_t: mpz_set_f)(X, Y)
> #endif

I'd say that like that, this is a very bad idea, because if the
compiler doesn't declare C11 support, the usual mpz_set function
would be used, and this could introduce obscure bugs.

For instance,

void foo (mpz_t z, long i)
  mpz_set (z, i);

compiles without any error with the current mpz_set function.

IMHO, the macro name needs to be different from mpz_set, or this
feature should explicitly be requested by the user, e.g. by defining
some GMP_* macro before including gmp.h (but be careful with the
possibility of multiple inclusions of gmp.h).

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-discuss mailing list