Advantage of switch over if-else statement

后端 未结 22 2377
梦谈多话
梦谈多话 2020-11-22 11:08

What\'s the best practice for using a switch statement vs using an if statement for 30 unsigned enumerations where about 10 have an ex

22条回答
  •  轮回少年
    2020-11-22 12:00

    Aesthetically I tend to favor this approach.

    unsigned int special_events[] = {
        ERROR_01,
        ERROR_07,
        ERROR_0A,
        ERROR_10,
        ERROR_15,
        ERROR_16,
        ERROR_20
     };
     int special_events_length = sizeof (special_events) / sizeof (unsigned int);
    
     void process_event(unsigned int numError) {
         for (int i = 0; i < special_events_length; i++) {
             if (numError == special_events[i]) {
                 fire_special_event();
                 break;
              }
         }
      }
    

    Make the data a little smarter so we can make the logic a little dumber.

    I realize it looks weird. Here's the inspiration (from how I'd do it in Python):

    special_events = [
        ERROR_01,
        ERROR_07,
        ERROR_0A,
        ERROR_10,
        ERROR_15,
        ERROR_16,
        ERROR_20,
        ]
    def process_event(numError):
        if numError in special_events:
             fire_special_event()
    

提交回复
热议问题