Home > Net >  c - conditional assignment of const, without ternary?
c - conditional assignment of const, without ternary?

Time:01-12

suppose I want to assign a const variable based on complex calculations which depend on a conditional.

if the situation were simple, I could do:

const int N = myBool ? 1 : 2;

but it's more like

const int N = myBool ? <lengthy calculation> : <other lengthy calculation>;

What I'm doing is this, but I'd like something cleaner:

int N_nonconst;
if (myBool) {
  N_nonconst = <lengthy calculation>;
}
else {
  N_nonconst = <other lengthy calculation>;
}
const int N = N_nonconst;

obviously, I could also do this:

int possibility1 = <lengthy calculation>;
int possibility2 = <other lengthy calculation>;
const in N = myBool ? possibility1 : possibility2;

but I'd like to actually perform only one of those lengthy calculations.

If I were extending the language, I'd consider making something like a const_deferredAssignment declaration:

const_deferredAssignment int N;
if (myBool) {
  N = <...>;
}
else {
  N = <...>;
}

I could also wrap those calculations up in functions/methods, but they use a bunch of locals, so it would be a fairly verbose function call.

CodePudding user response:

You could wrap each calculation in a lambda, and capture the local variables to reduce the verbosity of their arguments

{
    // ...

    auto firstFunc = [&]() -> int { ... };
    auto secondFunc = [&]() -> int { ... };
    
    const int N = myBool ? firstFunc() : secondFunc();
}

In this way only one of the two functions are actually executed.

CodePudding user response:

You could move the lengthy calculations to a separate function:

int lengthCalculation()
{
  if(myBool)
  {
    return <lengthy calculation>;
  }
  else
  {
    return <other lengthy calculation>;
  }
}

const int N = lengthCalculation();

If you don't want to create a separate function that you can use a local lambda:

const int N = [&]()
{
  if(myBool)
  {
    return <lengthy calculation>;
  }
  else
  {
    return <other lengthy calculation>;
   }
}();

CodePudding user response:

you could try and use

SWITCH(myBool) 
{

Case 0 : first_lengthy_calculation

         Break;

Case 1 : second_lengthy_calculation

         Break;

}
  •  Tags:  
  • Related