Converting the GNU case range extension to standard C

前端 未结 4 1420
猫巷女王i
猫巷女王i 2021-01-12 08:09

The GNU case range extension allows case ranges in switch statements:

switch (value) {
    case 1 ... 8:
        printf(\"Hello, 1 to 8\\n\");
        break;         


        
相关标签:
4条回答
  • 2021-01-12 08:20

    I would use an if statement:

    if (value >=1 && value <= 8) {
        printf("Hello, 1 to 8\n");
    } else {
        printf("Hello, default\n");
    } 
    

    You can then add extra else if statements if more ranges are required,

    0 讨论(0)
  • 2021-01-12 08:26

    Alternatively, since the numbers are adjacent to each other, you can do a manual optimization of the switch-case.

    typedef void(*func_t)(void);
    
    #define CASES_N 9
    
    void func0 (void)
    {
      printf("Hello, 0\n");
    }
    
    void func1 (void)
    {
      printf("Hello, 1 to 8\n");
    }
    
    static const func_t execute [CASES_N] =
    {
      &func0,
      &func1,
      &func1,
      &func1,
      &func1,
      &func1,
      &func1,
      &func1,
      &func1
    };
    
    int main()
    {
      if(what < CASES_N)
      {
        execute[what]();
      }
      else
      {
        printf("Hello, default\n");
      }
    }
    

    This code is basically the same as a compiler-optimized switch-statement.

    0 讨论(0)
  • 2021-01-12 08:30
    switch(value) 
    {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
            printf("Hello, 1 to 8\n"); 
            break;     
        default:         
            printf("Hello, default\n");         
            break; 
    } 
    

    EDIT: To answer the comment.
    If you have too many cases, then You might want to consider replacing the switch-case with if-else constructs. It can be much cleaner, concise & readable.

    if (value >=1 && value <= 8) 
    {    
        printf("Hello, 1 to 8\n"); 
    } 
    else 
    {   
        printf("Hello, default\n"); 
    }  
    
    0 讨论(0)
  • 2021-01-12 08:41

    If long long range you could do, a bit dirty but,

    switch(what) {
    case 1:
        /* do 1 */
        break;
    case 2:
        /* do 2 */
        break;
    default:
        if (what > 31 && what < 127) {
             /* do 32 to 126 */
        }
    }
    

    The best would probably be to remove the switch for an if all together.

    Be extremely strict with nesting. If you want the switch, for some reason, then better then the above would be:

    if (value > 31 && value < 127) {
      /* Do something */
    } else {
        switch (value) {
        case 1:
            ...
        }
    }
    

    Ach, sorry for edit again. This would be cleaner.

    if (value > 31 && value < 127) {
      /* Do something */
    } else if (value > 127 && value < 178) {
    
    } else if ( ...
    
    }
    
    switch (value) {
    case 1:
        ...
    }
    
    0 讨论(0)
提交回复
热议问题