Prevent use of functions before initialization, constructors like in C

Here is how I can prevent funA, funB, funC, etc. for use 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 any of these functions is called inside the loop, therefore, "if (initialized! = INIT_KEY)" is called again and again, although this is not necessary.

This is a good example of why constructors are useful haha. If it were an object, I would be sure that when it was created, initialization was called, but in C I don’t know how to do it.

Any other ideas are welcome!

+3
source share
5 answers

.

, , , .

- . , , . -... 0 . 1, , 2 1.

.

+5

- , :

#ifdef DEBUG
#  define ENSURE_INITIALIZED(obj) \
     do { \
         if (obj->initialized != INIT_CODE) { \
             fprintf (stderr, "Object %p not initliaized (%s:%d)\n", obj, __FILE__, __LINE__); \
             abort (); \
         } \
     } while (0)
#else
#  define ENSURE_INITIALIZED(obj)
#endif

voif foo (Object *obj) {
    ENSURE_INITIALIZED (obj);
}

, - .

abort , , .

+4

( ). "", . , EvilTeach.

+1

. , , ( ), . funX, , , funX , -.

, ( ).

, ,

if (!initialized) initialize();

, .

, , -. ( ).

,... . "" , ( , OO), , new MyClass() " "; "" ( , ), "" . , ,

Object a;
// ...
a.method(); //or

Object *a = new Object();
// ...
a->method();

init()
// ...
funA();

"" "", , , OO , "" .

, , ; , init, , "" .

+1

, ( ):

static int initResult = Init();

, , .

: undefined, ( - ). .

+1
source

Source: https://habr.com/ru/post/1749998/


All Articles