Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional statement true in both parts of if-else-if ladder

If you have code like this:

if (A > X && B > Y)
{
   Action1();
}
else if(A > X || B > Y)
{
   Action2();
}

With A > X and B > Y, will both parts of the if-else-if ladder be executed?

I'm dealing with Java code where this is present. I normally work in C++, but am an extremely new (and sporadic) programmer in both languages.

like image 762
traggatmot Avatar asked Oct 24 '14 15:10

traggatmot


Video Answer


4 Answers

No, they won't both execute. It goes in order of how you've written them, and logically this makes sense; Even though the second one reads 'else if', you can still think of it as 'else'.

Consider a typical if/else block:

if(true){
   // Blah
} else{
   // Blah blah
}

If your first statement is true, you don't even bother looking at what needs to be done in the else case, because it is irrelevant. Similarly, if you have 'if/elseif', you won't waste your time looking at succeeding blocks because the first one is true.

A real world example could be assigning grades. You might try something like this:

if(grade > 90){
   // Student gets A
} else if(grade > 80){
   // Student gets B
} else if(grade > 70){
   // Student gets c
}

If the student got a 99%, all of these conditions are true. However, you're not going to assign the student A, B and C.

That's why order is important. If I executed this code, and put the B block before the A block, you would assign that same student with a B instead of an A, because the A block wouldn't be executed.

like image 165
AdamMc331 Avatar answered Oct 01 '22 07:10

AdamMc331


If both A > X and B > Y are true then your code will only execute Action1. If one of the conditions is true it will execute Action2. If none are true, it will do nothing.

Using this:

if (A > X || B > Y) {
   Action2
   if (A > X && B > Y) {
      Action1                                    
   } 
}

will result in the possibility of both actions occurring when A > X and B > Y are both true.

like image 36
Grice Avatar answered Oct 01 '22 07:10

Grice


If you're talking about C, then only the first block that satisfies the condition is executed - after the control "enters" the conditional block it then "leaves" after all other conditions.

If you want such behavior, then just use two separate conditions - remove "else" and you have it.

like image 37
Freddie Chopin Avatar answered Oct 01 '22 08:10

Freddie Chopin


When the condition after if is true, only the first block is executed. The else block is only executed when the condition is false. It doesn't matter what's in the else block, it's not executed. The fact that the else block is another if statement is irrelevant; it won't be executed, so it will never perform the (A > X || B > X) test, and its body will not be executed even if that condition is true.

like image 25
Barmar Avatar answered Oct 01 '22 08:10

Barmar