Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between multiple if statements and else if?

Tags:

c

if-statement

If I write

int a = 1;
int b = 2;

if (a == b) {

//Do something

} else if (a > b) {

//Do something else

} else if (a < b) {

//Do something else

}

as opposed to:

if (a == b) {

//Do something

}
if (a > b) {

//Do something else

}
if (a < b) {

//Do something else

}

Is there a difference be it the way the compiler interprets the code or speed? I see no logical difference, but there surely must be a reason why an if else statement exists. It's just a single line break difference.

like image 584
Milo Avatar asked Mar 01 '14 06:03

Milo


People also ask

What is the difference between if if and if...else if?

Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.

Why use else if instead of multiple if?

Summary: By using an ELSE IF structure instead of multiple IF we can avoid “combined conditions” ( x<y && y<z ). Instead we can use a simplified condition (y<z). Furthermore ELSE IF is more efficient because the computer only has to check conditions until it finds a condition that returns the value TRUE.

What is the advantage of if...else statement over the if statement?

Advantages: if-else statement helps us to make decision in programming and execute the right code. It also helps in debugging of code.

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.


1 Answers

In the scenario above, they are the same, other than speed. If/else will be faster than a series of ifs, because else statements are skipped if the if condition is satisfied. In a series of ifs, on the other hand, each condition is evaluated separately.

In other scenarios, of course, the logic is not the same, and so replacing if/else with a series of ifs breaks the program. Example:

// this:
if(x <= 0) {
    x = 1;
}
else { // only true if x started out > 0
    x = 37;
}

// is different from this:
if(x <= 0) {
    x = 1;
}
if(x > 0) { // always true in this version
    x = 37;
}
like image 116
elixenide Avatar answered Nov 07 '22 22:11

elixenide