Search code examples
c++conditional-statementsconstantsvariable-assignment

c++ - conditional assignment of const, without ternary?


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.


Solution

  • 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.