Jumping from one case to the default case in switch statement

前端 未结 9 907
予麋鹿
予麋鹿 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:22

    If you must have the switch statements first because the condition you're checking for depends on the case (or the case has to be evaluated first before you can check on the condition), simply set a flag inside your switch cases, and if that flag is set, then do a default operation. For instance:

    int default_true = 0;
    switch (case_value)
    {
        case 'a': /* if the condition is true, set the default_true flag */
    
        case 'b': /* if the condition is true, set the default_true flag */
    
        //...
    
        default: default_flag = 1; // set the default_true flag to true
    }
    
    if (default_flag)
    {
        //place your "default" code here rather than inside the switch statement
        //this prevents code reduplication
    }
    
    0 讨论(0)
  • 2021-01-03 23:22

    I hope my solution answers your question. Simply let the cases follow through all the way (beginning with the matching case) but use a condition to disable subsequent cases from running.

    typedef enum boolean
    {
        FALSE = 0, TRUE = 1
    } bool;
    
    void pstuff(char input)
    {
        bool _skip = FALSE; 
        switch(input)
        {
            case 'a':
                printf("Case a.");
                _skip = TRUE; 
            case 'b': 
                if(!_skip)
                {
                    printf("Case b.");
                    _skip = TRUE;
                }
            case 'c':       
                if(!_skip)
                {
                    printf("Case c.");
                    _skip = TRUE; 
                }
            //...
            default: 
                printf("Done!\n"); //Always gets printed.
    
        }   
    }
    
    0 讨论(0)
  • 2021-01-03 23:23

    If the condition doesn't depend on cases, why put it inside?

    if (!condition){
      // do default
    }else{
      switch(ch){
        case 'a':
          // do a
          break;
        ...
      }
    }
    
    0 讨论(0)
提交回复
热议问题