Jumping from one case to the default case in switch statement

前端 未结 9 921
予麋鹿
予麋鹿 2021-01-03 22:59
switch(ch){
          case \'a\':
                 //do something, condition does not match so go to default case
                 //don\'t break in here, and don\'t         


        
9条回答
  •  情话喂你
    2021-01-03 23:04

    Refactor your code:

    int test_char(char ch)
    {
      switch(ch) {
        case 'a': if (condition) return 0; break;
        case 'b': // ...
        default: return -1;
      }
    
      return 1;
    }
    
    ... 
    // defaults processing switch
    switch(test_char(ch)) {
      case 0: break; // condition met
      case 1: // default processing
      default: // case not handled by test_char
    }
    

    This also adds the benefit of being flexible to test for multiple classes of default processing. Say you have a group of chars [c, d, e, f] which share some common logic. Simply return 2 from test_char() for these cases (possibly after some conditions has been tested), and add a case 2: handler to the default processing switch statement.

提交回复
热议问题