What is the difference between IF-ELSE and SWITCH?

后端 未结 6 2290
南方客
南方客 2020-11-29 06:43

Can someone please explain this to me?

6条回答
  •  北海茫月
    2020-11-29 07:09

    The difference between Switch and if-else statement is below:

    This is the general syntax of if-else ladder:

    if (condition1) { //Body of if }
        else if (condition2) { //Body of if }
        else if (condition3) { //Body of if }
    else { //default if all conditions return false }
    

    And this is the general syntax for switch:

    switch ( variable )
    {
     case : //Do Something
                                                 break;
     case ://Do Something
                                                 break;
     default: //Do Something
                    break;
    }
    

    The if-else ladder is of type strict condition check, while switch is of type jump value catching.

    Advantages of switch over if-else ladder:

    • A switch statement works much faster than equivalent if-else ladder. It is because compiler generates a jump table for a switch during compilation. Consequently, during execution, instead of checking which case is satisfied, it only decides which case has to be executed.
    • It is more readable and in compare to if-else statements.

提交回复
热议问题