switch/case statement in C++ with a QString type

amiref picture amiref · Mar 27, 2011 · Viewed 77.8k times · Source

I want to use switch-case in my program but the compiler gives me this error:

switch expression of type 'QString' is illegal

How can I use the switch statement with a QString?

My code is as follows:

bool isStopWord( QString word )
{
bool flag = false ;

switch( word )
{
case "the":
    flag = true ;
    break ;
case "at" :
    flag = true ;
    break ;
case "in" :
    flag = true ;
    break ;
case "your":
    flag = true ;
    break ;
case "near":
    flag = true ;
    break ;
case "all":
    flag = true ;
    break ;
case "this":
    flag = true ;
    break ;
}

return flag ;
}

Answer

AnT picture AnT · Mar 27, 2011

How can I use the switch statement with a QString?

You can't. In C++ language switch statement can only be used with integral or enum types. You can formally put an object of class type into a switch statement, but that simply means that the compiler will look for a user-defined conversion to convert it to integral or enum type.