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.
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.
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.
Advantages: if-else statement helps us to make decision in programming and execute the right code. It also helps in debugging of code.
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.
In the scenario above, they are the same, other than speed. If
/else
will be faster than a series of if
s, because else
statements are skipped if the if
condition is satisfied. In a series of if
s, 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 if
s 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;
}
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