Why the switch statement cannot be applied on strings?

前端 未结 20 2601
离开以前
离开以前 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:28

    Why not? You can use switch implementation with equivalent syntax and same semantics. The C language does not have objects and strings objects at all, but strings in C is null terminated strings referenced by pointer. The C++ language have possibility to make overload functions for objects comparision or checking objects equalities. As C as C++ is enough flexible to have such switch for strings for C language and for objects of any type that support comparaison or check equality for C++ language. And modern C++11 allow to have this switch implementation enough effective.

    Your code will be like this:

    std::string name = "Alice";
    
    std::string gender = "boy";
    std::string role;
    
    SWITCH(name)
      CASE("Alice")   FALL
      CASE("Carol")   gender = "girl"; FALL
      CASE("Bob")     FALL
      CASE("Dave")    role   = "participant"; BREAK
      CASE("Mallory") FALL
      CASE("Trudy")   role   = "attacker";    BREAK
      CASE("Peggy")   gender = "girl"; FALL
      CASE("Victor")  role   = "verifier";    BREAK
      DEFAULT         role   = "other";
    END
    
    // the role will be: "participant"
    // the gender will be: "girl"
    

    It is possible to use more complicated types for example std::pairs or any structs or classes that support equality operations (or comarisions for quick mode).

    Features

    • any type of data which support comparisions or checking equality
    • possibility to build cascading nested switch statemens.
    • possibility to break or fall through case statements
    • possibility to use non constatnt case expressions
    • possible to enable quick static/dynamic mode with tree searching (for C++11)

    Sintax differences with language switch is

    • uppercase keywords
    • need parentheses for CASE statement
    • semicolon ';' at end of statements is not allowed
    • colon ':' at CASE statement is not allowed
    • need one of BREAK or FALL keyword at end of CASE statement

    For C++97 language used linear search. For C++11 and more modern possible to use quick mode wuth tree search where return statement in CASE becoming not allowed. The C language implementation exists where char* type and zero-terminated string comparisions is used.

    Read more about this switch implementation.

提交回复
热议问题