I was perusing some code using arbitrary-length integers using the GNU Multi-Precision (GMP) library code. The type for a MP integer is mpz_t as defined in gmp.h header file.
But, I’ve some questions about the lower-level definition of this library-defined mpz_t type. In the header code:
/* THIS IS FROM THE GNU MP LIBRARY gmp.h HEADER FILE */
typedef struct
{
/* SOME OTHER STUFF HERE */
} __mpz_struct;
typedef __mpz_struct mpz_t[1];
First question: Does the [1] associate with the __mpz_struct? In other words, is the typedef defining a mpz_t type as a __mpz_struct array with one occurrence?
Second question: Why the array? (And why only one occurrence?) Is this one of those struct hacks I’ve heard about?
Third question (perhaps indirectly related to second question): The GMP documentation for the mpz_init_set(mpz_t, unsigned long int) function says to use it as pass-by-value only, although one would assume that this function would be modifying its contents within the called function (and thus would need pass-by-reference) syntax. Refer to my code:
/* FROM MY CODE */
mpz_t fact_val; /* declaration */
mpz_init_set_ui(fact_val, 1); /* Initialize fact_val */
Does the single-occurrence array enable pass-by-reference automatically (due to the breakdown of array/pointer semantics in C)? I freely admit I’m kinda over-analyzing this, but I’d certainly love any discussion on this. Thanks!
*First question: Does the
[1]associate with the __mpz_struct? In other words, is the typedef defining a mpz_t type as a __mpz_struct array with one occurrence?*Yes.
Second question: Why the array? (And why only one occurrence?) Is this one of those struct hacks I’ve heard about?
Beats me. Don’t know, but one possibility is that the author wanted to make an object that was passed by reference automatically, or, “yes”, possibly the struct hack. If you ever see an
mpz_tobject as the last member of a struct, then “almost certainly” it’s the struct hack. An allocation looking likewould be a dead giveaway.
Does the single-occurrence array enable pass-by-reference automatically…?
Aha, you figured it out too. “Yes”, one possible reason is to simplify pass-by-reference at the expense of more complex references.
I suppose another possibility is that something changed in the data model or the algorithm, and the author wanted to find every reference and change it in some way. A change in type like this would leave the program with the same base type but error-out every unconverted reference.