11

You can initialize a GMP variable 'mpz_t n' as mpz_init(n).

The documentation sais 'void mpz_inits (mpz_t x, ...) Initialize a NULL-terminated list of mpz_t variables, and set their values to 0.'

I'm not sure what a 'NULL-terminated list' here means.

mpz_t a, b, c;
mpz_inits(a, b, c, NULL);

Is the above the correct way to initialize a, b, and c?

  • 2
    Noteworthy, that this is not portable. An implementation may `#define` `NULL` to `0` (instead of `( (void *)0 )` like e.g. gcc is documented to do). You need `mpz_inits(a, b, c, (void *)NULL)` or `mpz_inits(a, b, c, (void *)0)`. – mafso Aug 06 '14 at 16:35
  • Just a note: "mpz_inits" and "mpz_clears" appeared with GMP 5.0.0. – SO Stinks Feb 13 '15 at 01:22

2 Answers2

10

Yes, this is correct.

In C, there's no implicit way for variadic functions (such as mpz_inits) to know how many arguments are passed. Different functions do this in different ways. For example, the *printf family uses the format string to decide the number/types of the extra arguments. In other cases, such as mpz_inits, they use a NULL-terminator to mark the end of the list (in much the same way that the null character \0 marks the end of a string).

NULL-terminated simply means that a list of otherwise indeterminate length has its end signaled by the NULL argument.

Drew McGowen
  • 11,471
  • 1
  • 31
  • 57
3

In C, when a prototype ends with an ellipsis, the types of the corresponding arguments cannot be checked. Thus you need to make sure that the type of the last argument is correct. Here, since mpz_inits expects pointers to mpz_ptr, you need to provide a null pointer to this type, e.g. by using a cast:

mpz_inits (a, b, c, (mpz_ptr) 0);

or

mpz_inits (a, b, c, (mpz_ptr) NULL);

Note that casting to another pointer type such as void * is not guaranteed to work on all platforms, in particular if the sizes of the pointer types are different. Now, whether such platforms exist / GMP supports such platforms is another problem... But other issues could also come from advanced compiler optimizations. So, it is better to strictly follow the C standard here.

vinc17
  • 2,829
  • 17
  • 23
  • @MarcGlisse Since this is the actual type used, `mpz_ptr` should be documented (a cast to `mpz_t`, which is the type documented for the prototype, doesn't work). – vinc17 May 11 '16 at 15:44