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?
Yes, we can use a switch statement with Strings in Java.
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.
No you can't. The case labels of a switch need to be compile time evaluable constant expressions with an integral type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With