Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the switch statement cannot be applied on strings?

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

int main() {     // Compilation error - switch expression of type illegal     switch(std::string("raj"))     {     case"sda":     } } 

You cannot use string in either switch or case. Why? Is there any solution that works nicely to support logic similar to switch on strings?

like image 668
yesraaj Avatar asked Mar 16 '09 12:03

yesraaj


People also ask

Can you use switch statements for strings?

Yes, we can use a switch statement with Strings in Java.

What Cannot be used in a switch statement?

The switch/case statement in the c language is defined by the language specification to use an int value, so you can not use a float value. The value of the 'expression' in a switch-case statement must be an integer, char, short, long. Float and double are not allowed.

Can switch statements use strings in C?

No you can't. The case labels of a switch need to be compile time evaluable constant expressions with an integral type.


1 Answers

The reason why has to do with the type system. C/C++ doesn't really support strings as a type. It does support the idea of a constant char array but it doesn't really fully understand the notion of a string.

In order to generate the code for a switch statement the compiler must understand what it means for two values to be equal. For items like ints and enums, this is a trivial bit comparison. But how should the compiler compare 2 string values? Case sensitive, insensitive, culture aware, etc ... Without a full awareness of a string this cannot be accurately answered.

Additionally, C/C++ switch statements are typically generated as branch tables. It's not nearly as easy to generate a branch table for a string style switch.

like image 196
JaredPar Avatar answered Oct 20 '22 19:10

JaredPar