Stack Danny Stack Danny - 3 months ago 7
C++ Question

Conditional Operator the only way to initialize global variables at a global scope?

Ok so I have a header file full of global variables.
here's an example how the implementation looks like (in the .cpp file):

extern double event::m_chance = 0.01;


Nothing special so far. But when my code became more complex, I started to implement a
#define MASTER_MODE
for testing purposes.
So now it looks like this:

extern double event::m_chance = MASTER_MODE ? 0.5 : 0.01;


and I asked myself: is this the only way to initialize global variables at a global scope (with a condition)?
since an if-statement does not work here... It must be, right?

//declarations
extern double event::m_chance;

if (MASTER_MODE) { //Error: excepted a declaration
event::m_chance = 0.5;
//other variables should be here
}
else { //nope
event::m_chance = 0.01;
//other variables should be here
}


I just ask myself if this is what everyone else does at my position. Or is there a nicer (standard-defined) way to init them.. (like making an extra function etc).

Thanks for your help / advices!

Answer
#ifdef MASTER_MODE

    extern double event::m_chance = 0.5;
    //other variables should be here

#else

    extern double event::m_chance = 0.01;
    //other variables should be here

#endif