prevent using functions before initialization, constructors-like in C
- by Hernán Eche
This is the way I get to prevent funA,funB,funC, etc.. for being used before init
#define INIT_KEY 0xC0DE //any number except 0, is ok
static int initialized=0;
int Init()
{
//many init task
initialized=INIT_KEY;
}
int funA()
{
if (initialized!=INIT_KEY) return 1
//..
}
int funB()
{
if (initialized!=INIT_KEY) return 1
//..
}
int funC()
{
if (initialized!=INIT_KEY) return 1
//..
}
The problem with this approach is that if some of those function is called within a loop
so "if (initialized!=INIT_KEY)" is called again, and again, although it's not necessary.
It's a good example of why constructors are useful haha, If it were an object I would be sure that when was created initialization was called, but in C, I don't know how to do it.
Any other ideas are welcome!