user
user

Reputation: 15

if/else or double if?

Are there any difference between using double (or triple,..)if instead of if/else branch, like

if(a==b)
{}
else if(a==c)
{}
else if(a==d)
{}

if(a==b)
{}
if(a==c)
{}
if(a==d)
{}

Thanks

Upvotes: 1

Views: 175

Answers (3)

zellio
zellio

Reputation: 32484

in this case

if ( conditional ) {
    //do stuff
}
else if ( conditional {
    //do stuff
} ... 

The system checks conditionals until it find a true value and then it does stuff.

In this case:

if ( conditional ) {
    //do stuff
}
if ( conditional ) {
    //do stuff
}

The system checks every conditional every time.

Upvotes: 3

keyboardP
keyboardP

Reputation: 69372

The second one will check all the conditions and if a, c and d were equal, for example, then both if(a==c) {} and if(a==d) {} would execute.

The first one would break away from the other checks once one of the condition is met.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

Yes, there is a difference. In the first case the evaluation will stop if one of the conditions is satisfied and others won't be evaluated whereas in the second case all conditions will be evaluated no matter if one is satisfied.

Upvotes: 5

Related Questions