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?
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.
To the question:
What are the benefits of an empty
else
clause in anelse 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With