Search code examples
c++if-statementfunction-pointersswitch-statementcontrol-flow

branching based on two boolean variables


Suppose I have two boolean variables, and I want to do completely different things based on their values. What is the cleanest way to achieve this?

Variant 1:

if (a && b)
{
    // ...
}
else if (a && !b)
{
    // ...
}
else if (!a && b)
{
    // ...
}
else
{
    // ...
}

Variant 2:

if (a)
{
    if (b)
    {
        // ...
    }
    else
    {
        // ...
    }
}
else
{
    if (b)
    {
        // ...
    }
    else
    {
        // ...
    }
}

Variant 3:

switch (a << 1 | b)
{
case 0:
    // ...
    break;

case 1:
    // ...
    break;

case 2:
    // ...
    break;

case 3:
    // ...
    break;
}

Variant 4:

lut[a][b]();

void (*lut[2][2])() = {false_false, false_true, true_false, true_true};

void false_false()
{
    // ...
}

void false_true()
{
    // ...
}

void true_false()
{
    // ...
}

void true_true()
{
    // ...
}

Are variants 3 and 4 too tricky/complicated for the average programmer? Any other variants I have missed?


Solution

  • The first variant is the clearest and most readable, but it can be adjusted:

    if (a && b) {
        // ...
    } else if (a) { // no need to test !b here - b==true would be the first case
        // ...
    } else if (b) { //no need to test !a here - that would be the first case
        // ...
    } else { // !a&&!b - the last remaining
        // ...
    }