QString in switch statement



  • Can't we use QString for comparision in switch statement like below,

    QString str = "TEMP";

    switch (str)
    {
    

    I tried to use like this but it didnot work.


  • Qt Champions 2016

    @ankit-thakar
    No, C++ doesn't allow for non-integral types in switch statements.

    Kind regards.



  • @ankit-thakar

    When you want to use a String in a switch statement, you obviosily know which String can be entered. In this case you can use enums.

    enum Strings { String1, String2, etc. }
    

    With this enums you're allowed to use the switch statement. Like

    Strings myString;
    
    switch (myString)
    {
     case Strings::String1:
      break;
     case Strings::String2:
      break;
     ...
     default:
      break;
    }
    

    So you can use the switch and it is readable in your code.


  • Qt Champions 2016

    @beecksche
    The inefficient part would be converting the string you have to a corresponding enum, and this pretty much defeats the whole purpose of having a duplicating enum and a switch construct.



  • Just use

    if (str == "...")
    {
       // ...
    }
    else if (str == "...")
    {
       // ...
    }
    //...
    else 
    {
        // ...
    }
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.