Why the switch statement cannot be applied on strings?

前端 未结 20 2909
离开以前
离开以前 2020-11-22 03:58

Compiling the following code and got the error of type illegal.

int main()
{
    // Compilation error - switch expression of type illegal
    sw         


        
20条回答
  •  借酒劲吻你
    2020-11-22 04:19

    The problem is that for reasons of optimization the switch statement in C++ does not work on anything but primitive types, and you can only compare them with compile time constants.

    Presumably the reason for the restriction is that the compiler is able to apply some form of optimization compiling the code down to one cmp instruction and a goto where the address is computed based on the value of the argument at runtime. Since branching and and loops don't play nicely with modern CPUs, this can be an important optimization.

    To go around this, I am afraid you will have to resort to if statements.

提交回复
热议问题