Should I prefer two if statements over an if-else statement if the conditions aren't related?

Viewed 148

So I know that generally speaking, I should prefer an else-if over and if if. But what if the two conditions aren't related? For example, these would be considered "related" conditionals:

if (line[a] == '{'){
    openCurly = true;
}
else if (line[a] == '}'){
    closeCurly = false;
}

Notice how the two conditionals in the if-statements are related in a way such that when one is true, the other must be false. This is because line[a] can either be { or } but not both.

Here is another example:

if (line[a] == '{')
{
    openCurly = true;
}
else if ((line[a] == ';' && !openCurly) || (line[a] == '}' && openCurly))
{
    DoSomething(line);
    line = "";
}

The second condition will never evaluate to true if the first condition if true, so it makes sense to have an else-if. However, those two conditionals look vastly different.

So, should I prefer something like this?

if (line[a] == '{')
{
    openCurly = true;
}

if ((line[a] == ';' && !openCurly) || (line[a] == '}' && openCurly))
{
    DoSomething(line);
    line = "";
}
2 Answers

You should use an else-if statement. This is because an if-else construct only checks the second statement if the first one doesn't evaluate to true.

In the example you give,

if (line[a] == '{')
{
    openCurly = true;
}
else if ((line[a] == ';' && !openCurly) || (line[a] == '}' && openCurly))
{
    DoSomething(line);
    line = "";
}

replacing the else if with an if statement would result in the second condition being checked even if the first one is true, which is completely pointless and would also lose you some time.

In the future, make decisions to use else-if statements based on whether the conditions are mutually exclusive or not.

You could do something like this:

#include <stdint.h>

#define COMBINATION(x,y) ((uint16_t(x)<<8)|(uint16_t(y)<<0))

...

    switch (COMBINATION(line[a],openCurly))
    {
    case COMBINATION('{',false):
        ...
        break;
    case COMBINATION(';',false):
    case COMBINATION('}',true):
        ...;
        break;
    }
}

Some may say it's a bit of an overkill, but I think that it may actually help splitting up the logical operation of your program into a set of distinct cases, thus make it easier to handle each case precisely as desired.

Related