Advantage of switch over if-else statement

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

    The switch is faster.

    Just try if/else-ing 30 different values inside a loop, and compare it to the same code using switch to see how much faster the switch is.

    Now, the switch has one real problem : The switch must know at compile time the values inside each case. This means that the following code:

    // WON'T COMPILE
    extern const int MY_VALUE ;
    
    void doSomething(const int p_iValue)
    {
        switch(p_iValue)
        {
           case MY_VALUE : /* do something */ ; break ;
           default : /* do something else */ ; break ;
        }
    }
    

    won't compile.

    Most people will then use defines (Aargh!), and others will declare and define constant variables in the same compilation unit. For example:

    // WILL COMPILE
    const int MY_VALUE = 25 ;
    
    void doSomething(const int p_iValue)
    {
        switch(p_iValue)
        {
           case MY_VALUE : /* do something */ ; break ;
           default : /* do something else */ ; break ;
        }
    }
    

    So, in the end, the developper must choose between "speed + clarity" vs. "code coupling".

    (Not that a switch can't be written to be confusing as hell... Most the switch I currently see are of this "confusing" category"... But this is another story...)

    Edit 2008-09-21:

    bk1e added the following comment: "Defining constants as enums in a header file is another way to handle this".

    Of course it is.

    The point of an extern type was to decouple the value from the source. Defining this value as a macro, as a simple const int declaration, or even as an enum has the side-effect of inlining the value. Thus, should the define, the enum value, or the const int value change, a recompilation would be needed. The extern declaration means the there is no need to recompile in case of value change, but in the other hand, makes it impossible to use switch. The conclusion being Using switch will increase coupling between the switch code and the variables used as cases. When it is Ok, then use switch. When it isn't, then, no surprise.

    .

    Edit 2013-01-15:

    Vlad Lazarenko commented on my answer, giving a link to his in-depth study of the assembly code generated by a switch. Very enlightning: http://lazarenko.me/switch/

提交回复
热议问题