Advantage of switch over if-else statement

后端 未结 22 2525
梦谈多话
梦谈多话 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 11:44

    I would say use SWITCH. This way you only have to implement differing outcomes. Your ten identical cases can use the default. Should one change all you need to is explicitly implement the change, no need to edit the default. It's also far easier to add or remove cases from a SWITCH than to edit IF and ELSEIF.

    switch(numerror){
        ERROR_20 : { fire_special_event(); } break;
        default : { null; } break;
    }
    

    Maybe even test your condition (in this case numerror) against a list of possibilities, an array perhaps so your SWITCH isn't even used unless there definately will be an outcome.

提交回复
热议问题