Why We Use If, Else If Instead of Multiple If Block If the Body Is a Return Statement

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

If Else VS Multiple If Statements

Using only if, interpreter or whatever will test all conditions but if you use else if (if possible) then on passing any condition , next else if will not be tested or checked.

if (age < 10){
// do something
}
if (age < 20 && age > 10){
// do something
}
if (age < 30 && age > 20){
// do something
}

All conditions will be tested/compared

but in this scenario

if (age < 10){
// do something
}
else if (age < 20 && age > 10){
// do something
}
else if (age < 30 && age > 20){
// do something
}

if age is 5, only first condition will be tested.

Using multiple if statements instead of else if when each statement return something

It has anything to do with being reacheable ot not. If is is not empty then the else will be reached.

I think that once it gets inside the first if flow will return then there is no point in the else. In other words else does not add anything therefore it is noise. There are people that prefer having else. Personally I believe without else code is easier to understand.

What's the difference between using an else if statement and just creating a new if statement?

The big difference is that with the else, the second condition will not be checked at all if the first condition was true. Without the else, the second condition will be checked.

Ramifications of that:

  • If the conditions are not mutually-exclusive, without the else both could match and both if bodies could be executed.
  • If the conditions involve side effects, without the else the second evaluation will trigger the side-effect a second time.
  • As dasblinkenlight pointed out in a now-deleted comment below (and now in his answer), if x is a volatile field and its value is changed by another thread after the first check and before the second, without the else both conditions could match and both if bodies could be executed.

To see what I mean about evaluation, let's make x a function call with a side effect instead of just a variable (Java and JavaScript are very different, but in this case, we can use JavaScript to demonstrate the concept):

function x() {

console.log("x called");

return 42;

}

console.log("With else:");

if (x() > 1) {

console.log("> 1");

} else if (x() < 1) {

console.log("< 1");

}

console.log("Without else:");

if (x() > 1) {

console.log("> 1");

}

if (x() < 1) {

console.log("< 1");

}
.as-console-wrapper {

max-height: 100% !important;

}

Are multiple 'if' statements and 'if-else-if' statements the same for mutually exclusive conditions?

When you write multiple if statements, it's possible that more than one of them will be evaluated to true, since the statements are independent of each other.

When you write a single if else-if else-if ... else statement, only one condition can be evaluated to true (once the first condition that evaluates to true is found, the next else-if conditions are skipped).

You can make multiple if statements behave like a single if else-if .. else statement if each of the condition blocks breaks out of the block that contains the if statements (for example, by returning from the method or breaking from a loop).

For example :

public void foo (int x)
{
if (x>7) {
...
return;
}
if (x>5) {
...
return;
}
}

Will have the same behavior as :

public void foo (int x)
{
if (x>7) {
...
}
else if (x>5) {
...
}
}

But without the return statements it will have different behavior when x>5 and x>7 are both true.

Why does the program give me a different result when I use if statement

In an if else-if statement you put multiple conditions to evaluate the result.

The following is how the statements will work in your case:

if(row==1||row==n||row==2*n-1)
cout<<"*"; //if true then put * or if false then move down
else if (col==1&&row<n||col==n&&row>n)
cout<<"*"; // if the first is false and the 2nd one is true then put * or if false then move down
else
cout<<" "; // if both of the above statements are not true put whitespace

I hope it helps.

Update: (from the OP's comment)

if(row==1||row==n||row==2*n-1)
cout<<"*"; // if the above is true then show *
else
cout<<" "; // else show whitespace

if (col==1&&row<n||col==n&&row>n)
cout<<"*"; // if the above is true show *
else
cout<<" "; // else show whitespace

In this code the first and second statements work independently and there is nothing related in them. If the first one is true or false it doesn't matter to the second one and vice versa.

Furthermore, you can omit the else statement if you don't need it.

if (col==1&&row<n||col==n&&row>n)
cout<<"*"; // if the above is true show *
// here else will not show whitespace because it is omitted

What is better: multiple if statements or one if with multiple conditions?

One golden rule I follow is to "Avoid Nesting" as much as I can. But if it is at the cost of making my single if condition too complex, I don't mind nesting it out.

Besides you're using the short-circuit && operator. So if the boolean is false, it won't even try matching!

So,

if (boolean_condition && matcher.find(string)) {
...
}

is the way to go!

Programming preference - use else ifs with multiple return statements?

Some would say that multiples return would be the problem here. But it's not really my point.

For my point of view, the if/else if is really important, because even if in your case you return some value, removing the elses would mean that you wouldn't put them anyway, and that would mean a totally different thing if the returns were not here.

Plus, imagine someday someone want to edit your code, and clean it up for a single return, this person could misunderstand your code and do a grave mistake like this :

public String getTemperatureMessage(double temp){
String message;
if(temp < 32)
message = "Freezing";
if(temp < 60)
message = "Brr";
if(temp < 80)
message = "Comfortable";
else
message = "Too hot";
return message;
}

To clarify my point of view, keep the elses, it keep your code clear.



Related Topics



Leave a reply



Submit