Home > Net >  Is there a way to conditionally initialize a global static variable?
Is there a way to conditionally initialize a global static variable?

Time:11-16

So my current code looks like the following:

static Item fields[] = 
{
{GROUP1, TEXT1},
{GROUP2, 0},
}

Now I need to make change in such a way that I initialize GROUP2 only if certain condition is met else need to initialize with GROUP3. So I tried the following:

static Item fields[] = (flagSet)?
{
{GROUP1, TEXT1},
{GROUP2, 0},
} : {
{GROUP1, TEXT1},
{GROUP3, 0},
}

But this didn't work. I know that one way is to use #ifdef macros but this flagSet happens at runtime and based on that I need to initialize the static array. Also since the static initialization happens before anything else is it possible to do this at all?

CodePudding user response:

Is there a way to conditionally initialize a global static variable?

Yes. The ways are pretty much the same as conditionally initialising a non-global non-static variable.

You cannot however conditionally initialise an array. You could use a bit of indirection:

static Item fields_true[] {
    {GROUP1, TEXT1},
    {GROUP2, 0},
};

static Item fields_false[] = {
    {GROUP1, TEXT1},
    {GROUP3, 0},
};

static auto& fields =
      flagSet
    ? fields_true
    : fields_false;

Or, you could initialise the array elements conditionally. Since only one element has a difference, there isn't even any repetition in this case:

static Item fields[] = {
    {GROUP1, TEXT1},
    {flagSet ? GROUP2 : GROUP3, 0},
};

but this flagSet happens at runtime

Using runtime input is not an option to initialise static objects. You will have to modify the array after initiliasation using assignment operation.

  • Related