Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between using multiple if statements and else if statements?

This question pertains specifically to shell scripts, but could be about any programming language.

Is there any difference between using multiple if statements and using elif statements in shell scripts? And, a case statement would not work in my situation.

like image 559
Mark Szymanski Avatar asked Jan 08 '11 21:01

Mark Szymanski


People also ask

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 better than multiple if statements?

Switch statement works better than multiple if statements when you are giving input directly without any condition checking in the statements. Switch statement works well when you want to increase the readability of the code and many alternative available.

Is it bad to have multiple if statements?

In this case it is fine, in fact in most cases it is. The problem only occurs when you have many nested in many and so it can become hard to read and you may forget something, but that's readability, there is nothing wrong in the logic for using nested if statements.


1 Answers

Yes, potentially. Consider this (C#, Java, whatever):

int x = GetValueFromSomewhere();  if (x == 0) {     // Something     x = 1; } else if (x == 1) {     // Something else... } 

vs this:

int x = GetValueFromSomewhere();  if (x == 0) {     // Something     x = 1; } if (x == 1) {     // Something else... } 

In the first case, only one of "Something" or "Something else..." will occur. In the second case, the side-effects of the first block make the condition in the second block true.

Then for another example, the conditions may not be mutually exclusive to start with:

int x = ...;  if (x < 10) {     ... }  else if (x < 100) {     ... } else if (x < 1000) {     ... } 

If you get rid of the "else" here, then as soon as one condition has matched, the rest will too.

like image 188
Jon Skeet Avatar answered Oct 07 '22 21:10

Jon Skeet