Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"if' VS "else if"

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?

like image 245
kofucii Avatar asked Sep 24 '10 19:09

kofucii


People also ask

Which is better if or else if?

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.

What is the difference between if else and Elif?

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.

What is difference between if/then and if/then else?

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.

Can I use only if and else if?

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.


1 Answers

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.

like image 170
KeithS Avatar answered Nov 16 '22 01:11

KeithS