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

后端 未结 4 1809
情话喂你
情话喂你 2020-12-10 09:02

If you have code like this:

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

With

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-10 09:20

    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.

提交回复
热议问题