Why we use if, else if instead of multiple if block if the body is a return statement

if-elseif-else statements stop doing comparisons as soon as it finds one that's true. if-if-if does every comparison. The first is more efficient.

Edit: It's been pointed out in comments that you do a return within each if block. In these cases, or in cases where control will leave the method (exceptions), there is no difference between doing multiple if statements and doing if-elseif-else statements.

However, it's best practice to use if-elseif-else anyhow. Suppose you change your code such that you don't do a return in every if block. Then, to remain efficient, you'd also have to change to an if-elseif-else idiom. Having it be if-elseif-else from the beginning saves you edits in the future, and is clearer to people reading your code (witness the misinterpretation I just gave you by doing a skim-over of your code!).


What about the case where b1 == b2? (And if a == b1 and a == b2?)

When that happens, generally speaking, the following two chunks of code will very likely have different behavior:

if (a == b1) {
   /* do stuff here, and break out of the test */
} 
else if (a == b2) {
   /* this block is never reached */
} 

and:

if (a == b1) {
   /* do stuff here */
}
if (a == b2) {
   /* do this stuff, as well */
}

If you want to clearly delineate functionality for the different cases, use if-else or switch-case to make one test.

If you want different functionality for multiple cases, then use multiple if blocks as separate tests.

It's not a question of "best practices" so much as defining whether you have one test or multiple tests.


The are NOT functionally equivalent.

The only way it would be functionally equivalent is if you did an "if" statement for every single possible value of a (ie: every possibly int value, as defined in limits.h in C; using INT_MIN and INT_MAX, or equivalent in Java).

The else statement allows you to cover every possible remaining value without having to write millions of "if" statements.

Also, it's better coding practice to use if...else if...else, just like how in a switch/case statement, your compiler will nag you with a warning if you don't provide a "default" case statement. This prevents you from overlooking invalid values in your program. eg:

double square_root(double x) {
    if(x > 0.0f) {
        return sqrt(x);
    } else if(x == 0.0f) {
        return x;
    } else {
        printf("INVALID VALUE: x must be greater than zero");
        return 0.0f;
    }
}

Do you want to type millions of if statements for each possible value of x in this case? Doubt it :)

Cheers!

Tags:

C++

Java