48

I am always in the habit of using if, else-if statement instead of multiple if statements.

Example:

int val = -1;
if (a == b1) {
   return c1;
} else if (a == b2) {
   return c2;
} ...
...
} else {
   return c11;
}

How does it compare to example 2:

if (a == b1) {
   return c1;
}
if (a == b2) {
   return c2;
}
....

if (a == b11) {
   return c11;
}

I know functionality wise they are the same. But is it best practice to do if else-if, or not? It's raised by one of my friends when I pointed out he could structure the code base differently to make it cleaner. It's already a habit for me for long but I have never asked why.

Ken Bloom
  • 57,498
  • 14
  • 111
  • 168
Lily
  • 5,872
  • 19
  • 56
  • 75
  • 1
    Which language are you referring to? Java or C++? – Billjk Feb 07 '12 at 00:12
  • it's java for me, but I have been using it for both c++ and Java for long... – Lily Feb 07 '12 at 00:15
  • 4
    It's a significant difference, because you can implement `operator==` in C++ to do nasty (side-effecty) things (which has also an influence on optimisation ...). AFAICR this doesn't work in Java. – bitmask Feb 07 '12 at 00:41
  • Sometimes it's efficient to use if-if-if block statements because of comparing different variable types. Like in JAVA I'm checking if name,price,amount all have values. Since name is String and price & amount are int, I would have to do a separate if statements. It depends on what situation you're dealing with. – MJ DLS Nov 13 '21 at 16:08

13 Answers13

90

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!).

Community
  • 1
  • 1
CanSpice
  • 34,814
  • 10
  • 72
  • 86
16

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.

Alex Reynolds
  • 95,983
  • 54
  • 240
  • 345
8

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!

Cloud
  • 18,753
  • 15
  • 79
  • 153
  • +1 for pointing out that they are not functionally equivalent. – Perception Feb 07 '12 at 00:55
  • 7
    If we have a return in every if codeblock they are equivalent. The invalid value part just isn't in an else block but instead normal code after the last if. Perfectly functionally equivalent. Even without the return statement we can get the functionally equivalent code apart from the fact that we do one additional check for each if (although a good compiler could remove that as well) – Voo Feb 07 '12 at 01:33
3

This totally depends on the condition you're testing. In your example it will make no difference eventually but as best practice, if you want ONE of the conditions to be eventually executed then you better use if else

if (x > 1) {
    System.out.println("Hello!");
}else if (x < 1) {
    System.out.println("Bye!");
}

Also note that if the first condition is TRUE the second will NOT be checked at all but if you use

if (x > 1) {
    System.out.println("Hello!");
}
if (x < 1) {
    System.out.println("Bye!");
}

The second condition will be checked even if the first condition is TRUE. This might be resolved by the optimizer eventually but as far as I know it behaves that way. Also the first one is the one is meant to be written and behaves like this so it is always the best choice for me unless the logic requires otherwise.

Anddo
  • 2,144
  • 1
  • 14
  • 33
1

I prefer if/else structures, because it's much easier to evaluate all possible states of your problem in every variation together with switches. It's more robust I find and quicker to debug especially when you do multiple Boolean evaluations in a weak-typed environment such as PHP, example why elseif is bad (exaggerated for demonstration):

if(a && (c == d))
{
} elseif ( b && (!d || a))
{
} elseif ( d == a && ( b^2 > c))
{
} else {
}

This problem has beyond 4^2=16 boolean states, which is simply to demonstrate the weak-typing effects that makes things even worse. It isn't so hard to imagine a three state variable, three variable problem involved in a if ab elseif bc type of way.

Leave optimization to the compiler.

1

In most cases, using if-elseif-else and switch statements over if-if-if statements is more efficient (since it makes it easier for the compiler to create jump/lookup tables) and better practice since it makes your code more readable, plus the compiler makes sure you include a default case in the switch. This answer, along with this table comparing the three different statements was synthesized using other answer posts on this page as well as those of a similar SO question.

janeon
  • 59
  • 4
1

if and else if is different to two consecutive if statements. In the first, when the CPU takes the first if branch the else if won't be checked. In the two consecutive if statements, even if the the first if is checked and taken, the next if will also be check and take if the the condition is true.

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
1

I tend to think that using else if is easier more robust in the face of code changes. If someone were to adjust the control flow of the function and replaces a return with side-effect or a function call with a try-catch the else-if would fail hard if all conditions are truly exclusive. It really depends to much on the exact code you are working with to make a general judgment and you need to consider the possible trade-offs with brevity.

pmr
  • 58,701
  • 10
  • 113
  • 156
1

With return statements in each if branch.

In your code, you have return statements in each of the if conditions. When you have a situation like this, there are two ways to write this. The first is how you've written it in Example 1:

if (a == b1) {
   return c1;
} else if (a == b2) {
   return c2;
} else {
   return c11;
}

The other is as follows:

if (a == b1) {
   return c1;
}
if (a == b2) {
   return c2;
}
return c11; // no if or else around this return statement

These two ways of writing your code are identical.

The way you wrote your code in example 2 wouldn't compile in C++ or Java (and would be undefined behavior in C), because the compiler doesn't know that you've covered all possible values of a so it thinks there's a code path through the function that can get you to the end of the function without returning a return value.

if (a == b1) {
   return c1;
}
if (a == b2) {
   return c2;
}
...
if (a == b11) {
   return c11;
}
// what if you set a to some value c12?

Without return statements in each if branch.

Without return statements in each if branch, your code would be functionally identical only if the following statements are true:

  1. You don't mutate the value of a in any of the if branches.
  2. == is an equivalence relation (in the mathematical sense) and none of the b1 thru b11 are in the same equivalence class.
  3. == doesn't have any side effects.

To clarify further about point #2 (and also point #3):

  • == is always an equivalence relation in C or Java and never has side effects.
  • In languages that let you override the == operator, such as C++, Ruby, or Scala, the overridden == operator may not be an equivalence relation, and it may have side effects. We certainly hope that whoever overrides the == operator was sane enough to write an equivalence relation that doesn't have side effects, but there's no guarantee.
  • In JavaScript and certain other programming languages with loose type conversion rules, there are cases built into the language where == is not transitive, or not symmetric. (In Javascript, === is an equivalence relation.)

In terms of performance, example #1 is guaranteed not to perform any comparisons after the one that matches. It may be possible for the compiler to optimize #2 to skip the extra comparisons, but it's unlikely. In the following example, it probably can't, and if the strings are long, the extra comparisons aren't cheap.

if (strcmp(str, "b1") == 0) {
  ...
}
if (strcmp(str, "b2") == 0) {
  ...
}
if (strcmp(str, "b3") == 0) {
  ...
}
Ken Bloom
  • 57,498
  • 14
  • 111
  • 168
0

I think these code snippets are equivalent for the simple reason that you have many return statements. If you had a single return statements, you would be using else constructs that here are unnecessary.

Alessandro Santini
  • 1,943
  • 13
  • 17
0

Your comparison relies on the fact that the body of the if statements return control from the method. Otherwise, the functionality would be different.

In this case, they perform the same functionality. The latter is much easier to read and understand in my opinion and would be my choice as which to use.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
0

They potentially do different things.

If a is equal to b1 and b2, you enter two if blocks. In the first example, you only ever enter one. I imagine the first example is faster as the compiler probably does have to check each condition sequentially as certain comparison rules may apply to the object. It may be able to optimise them out... but if you only want one to be entered, the first approach is more obvious, less likely to lead to developer mistake or inefficient code, so I'd definitely recommend that.

Philluminati
  • 2,649
  • 2
  • 25
  • 32
0

CanSpice's answer is correct. An additional consideration for performance is to find out which conditional occurs most often. For example, if a==b1 only occurs 1% of the time, then you get better performance by checking the other case first.

Gir Loves Tacos answer is also good. Best practice is to ensure you have all cases covered.

jhsowter
  • 619
  • 3
  • 8