prevent using functions before initialization, constructors-like in C

Posted by Hernán Eche on Stack Overflow See other posts from Stack Overflow or by Hernán Eche
Published on 2010-06-14T19:55:22Z Indexed on 2010/06/14 20:02 UTC
Read the original article Hit count: 237

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!

© Stack Overflow or respective owner

Related posts about c

    Related posts about optimization