Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an empty "else" clause have any significance in C++?

Is there any difference between the following 2 codes functionally? If not, is there a preferred style?

int main()
{
    int i=11;

    if (i > 100)
    {
        i = 100;
    }
    else if (i < 0)
    {
        i = 0;
    }

    cout << i << endl;
}

versus

int main()
{
    int i=11;

    if (i > 100)
    {
        i = 100;
    }
    else if (i < 0)
    {
        i = 0;
    }
    else
    {
    }

    cout << i << endl;
}

In other words, my question is, is there any point in including the else if I don't want it to do anything?

like image 517
David Avatar asked Feb 14 '16 04:02

David


1 Answers

Significance

To the question:

...does an empty else clause have any significance?

in the context of if { ... } else {} the answer is no. Compilers will probably optimize your else out. Unless you put actual statements (assert, print, error handling) the executable will be virtually identical.


Benefits

To the question:

What are the benefits of an empty else clause in an else if construct?

the answer is discussed at length on this Stack Overflow post. See MISRA publication MISRA C:2012, 15.7 (All if…​else if constructs shall be terminated with an else statement).
It applies to if { ... } else if { ... } else {} construct, not if { ... } else {} construct.


Style

An else { /* no statement */ } in immensely better than an else statement. It does prevent dangling else closures (else not followed by {}) which are downright dangerous since they may mislead a reader of what else actually applies to, and is prone to maintenance errors.

You will find more programming styles1 than you have engineers in a room. May I suggest:

int main() {
    int i = 11;

    if (i > 100) {
        i = 100;
    } else if (i < 0) {
        i = 0;
    }

    cout << i << endl;
}

1 each individual, plus one for the consensus.

like image 162
SwiftArchitect Avatar answered Oct 03 '22 22:10

SwiftArchitect