Converting the GNU case range extension to standard C

前端 未结 4 1449
猫巷女王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: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.

提交回复
热议问题