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

折月煮酒 提交于 2019-12-30 09:54:33

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/26550990/conditional-statement-true-in-both-parts-of-if-else-if-ladder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!