Advantage of switch over if-else statement

后端 未结 22 2521
梦谈多话
梦谈多话 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

    For the special case that you've provided in your example, the clearest code is probably:

    if (RequiresSpecialEvent(numError))
        fire_special_event();
    

    Obviously this just moves the problem to a different area of the code, but now you have the opportunity to reuse this test. You also have more options for how to solve it. You could use std::set, for example:

    bool RequiresSpecialEvent(int numError)
    {
        return specialSet.find(numError) != specialSet.end();
    }
    

    I'm not suggesting that this is the best implementation of RequiresSpecialEvent, just that it's an option. You can still use a switch or if-else chain, or a lookup table, or some bit-manipulation on the value, whatever. The more obscure your decision process becomes, the more value you'll derive from having it in an isolated function.

提交回复
热议问题