Home > Back-end >  C elegant way to combine switch with if and variable assignment
C elegant way to combine switch with if and variable assignment

Time:12-21

My code looks like this

enum possible_cases; //assigned somewhere
bool decision; //assigned somewhere

//basically the default action for my possible_cases
int value = 10;
do_something(value);

switch (possible_cases)
{
    case 0:
        //assume covered by do_something(value)
        break;
    case 1:
        if ( decision )
        {
            value = get_other_value();
            do_something(value);
        }
        break;
    case 2:
        value = get_other_value(); //will return same value as in case 1
        do_something(value);
        break;
}

As you see

  1. it has to run do_something() with one specific value
  2. it might have to run do_something() with other values additionally, and the list of cases might grow, to a point, where having bools is impractical

but overall I am not happy as it is kinda redundant and I think there is a way to do it better.

I would like to stay with enum of cases

Edit:

It seems not clear where the problem is:

I see the call of the same function in 3 places, while I assume I could reduce it to 2 as I know I need to run it only 2 times at max. It is really more the aesthetic aspect

CodePudding user response:

The redundant part in your code is do_something(value) So I would suggest you to separate that part of the code

enum possible_cases; //assigned somewhere
bool decision; //assigned somewhere

//basically the default action for my possible_cases
int value = 10;

switch (possible_cases)
{
    case 1:
        if ( decision )
            value = get_other_value();
        break;
    case 2:
        value = get_other_value(); //will return same value as in case 1
        break;
}
do_something(value);

CodePudding user response:

By adding extra layer you might do:

std::optional<int>
get_additionnal_value(Epossible_cases possible_cases, bool decision)
{
    //basically the default action for my possible_cases
    const int value = 10;
    
    switch (possible_cases)
    {
    default:
    case 0: return std::nullopt;
#if 1
    case 1: return decision ? get_other_value() : value;
#else
    case 1: if (!decision) return value;
            [[fallthrough]];
#endif
    case 2: return get_other_value(); //will return same value as in case 1
    }
}

and then

do_something(10);
if (auto opt_value = get_additionnal_value(possible_cases, decision)) {
    do_something(opt_value);
}
  • Related