I'd been told, that using "if" statements is preferred , because of harder debugging of the code, when "else if" is used? Is there a grain of truth in this statement?
In general, "else if" style can be faster because in the series of ifs, every condition is checked one after the other; in an "else if" chain, once one condition is matched, the rest are bypassed.
The elif is short for else if. It allows us to check for multiple expressions. If the condition for if is False , it checks the condition of the next elif block and so on. If all the conditions are False , the body of else is executed.
When an If ... Then ... Else statement is encountered, condition is tested. If condition is True , the statements following Then are executed. If condition is False , each ElseIf statement (if there are any) is evaluated in order.
In your case, whether you need an else clause depends on whether you want specific code to run if and only if neither of condition1 , condition2 , and condition3 are true. else can be omitted for any if statement, there is nothing special in the last if of an if / else if chain.
if(...)
{
}
else if(...)
{
}
is completely equivalent to:
if(...)
{
}
else
if(...)
{
}
in the same way that:
if(...)
foo();
else
bar();
is totally equivalent to:
if(...) foo();
else bar();
It's 100% style, and whether one is more or less readable than another is a total judgment call based on your programming culture, language and how complex the statement is.
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