c++performance

Safety of if statement and if-else statement


My question may be weird or even unnecessary. Will it do any harm to always satisfy the condition in if statement and omit else like snippet 1?

if (condition 1) {

    // code here

    if (condition 2) {

        // code here

    }
}

Or, is snippet 2 better?

if (condition 1) {

    // code here

    if (!condition 2) {
        return;
    }

    else {

        // code here

    }
}

Solution

  • Some guidelines (in the automotive industry, for example) specify that the else statement must be included, even if it's empty. In that case, you can make a comment inside the else statement specifying that you actually don't want to do anything inside it.

    One advantage that I can think of is this. If you have:

    if (condition)
        doSomething();
    doSomethingElse();
    

    In this scenario, the if case will execute doSomething() and the else case will execute doSomethingElse(). If you now modify your code like this:

    if (condition)
        doSomething();
    doSomethingElse();
    doAnother();
    

    what do you think will happen? The else case will execute only doSomethingElse(). The doAnother() will execute in both cases (if and else). But is this really what you want? Maybe it is, maybe it isn't. Maybe you wanted something like:

    if (condition) 
    {
        doSomething();
    }
    else
    {
        doSomethingElse();
        doAnother();
    }
    

    In this situation, doAnother() clearly belongs to the else case.

    So, specify the else explicitly when you have code that changes frequently or it's modified by more than one developer. It really makes things clearer and avoids mistakes/bugs in the code.