Reputation: 305
We know that for a static variable, the following code is wrong.
//this fails: can't call gsl_vector_alloc() before main() starts
static gsl_vector *scratch = gsl_vector_alloc(20);
We can solve this by using a macro.
The book says we have to [start at zero and allocate on first use]
#define Staticdef(type, var, initialization) \
static type var = 0; \
if (!(var)) var = (initialization);
//usage:
Staticdef(gsl_vector*, scratch, gsl_vector_alloc(20));
I don't understand:
why can't I just write:
#define Staticdef(type, var, initialization) \
static type var = (initialization);
"This works as long as we don’t ever expect initialization to be zero (or in pointer-speak, NULL). If it is, it’ll get reinitialized on the next go-round." I don't understand why it'll get REinitialized. [I know static variables can be initialized once and will remember its value even if the frame dies, which will be used to count how many times a function gets called]
I am a new C programmer, so be kind with me if my question seems obvious. Thank you in advance!
OK, I now fully understand point 1 and point 3 above, for point 2, I think [allocate on first use] has something to do with that gsl_vector_alloc() function, but I am still not sure about point 4.
Upvotes: 0
Views: 82
Reputation: 68023
The static local variables are initializes only ones and retain their value between the calls.
But the idea of this code is extremely bad. It can be considered only for the pointer types.
Why. Because it hard to make zero an illegal value for the integer types.
Generally speaking IMO using this macro in this code is pointless and only makes code harder to read and more error prone
Upvotes: 1