Switch statement: must default be the last case?

后端 未结 10 2162
面向向阳花
面向向阳花 2020-11-27 02:36

Consider the following switch statement:

switch( value )
{
  case 1:
    return 1;
  default:
    value++;
    // fall-through
  case 2:
    ret         


        
10条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 03:18

    The case statements and the default statement can occur in any order in the switch statement. The default clause is an optional clause that is matched if none of the constants in the case statements can be matched.

    Good Example :-

    switch(5) {
      case 1:
        echo "1";
        break;
      case 2:
      default:
        echo "2, default";
        break;
      case 3;
        echo "3";
        break;
    }
    
    
    Outputs '2,default'
    

    very useful if you want your cases to be presented in a logical order in the code (as in, not saying case 1, case 3, case 2/default) and your cases are very long so you do not want to repeat the entire case code at the bottom for the default

提交回复
热议问题