Cant strings be used in a switch statement?
C++
Certainly.
Strings are not a type in c++, therefore they can not be used in a switch.
They cannot be used as cleanly as an int, but then ease was not offered as a criteria.
What is it you are trying to accomplish?
As you can see in the link, a string is type char. Assorted types of char may be done in a switch case, but not a string which is a class library for special char array handling. http://www.cplusplus.com/reference/string/string/?kw=string In contrast, all the standard types of ints: http://www.cplusplus.com/reference/cstdint/ That is why you can't just use a string in a switch case. It does not have the added logic to handle non-typed objects. This is a side effect of the way C and C++ are strongly typed languages, in contrast to Python, which is loosely typed. Oh, and type char is actually just a special type of int.
Thanks
Not to confuse the issue, but technically it can be done although not cleanly. It all depends on how much work you want to put into it. http://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4067/Switch-on-Strings-in-C.htm
Ah, but that does not use the string in the switch case. It uses the string in a function. You should be able to get similar results by converting the string to a cstring, or character array. Then it is a typed object just like what that example does. So the best you can do is indirectly use a sting in a switch case, but there is no way to use one directly. Welcome to the world of strongly typed C++. I still wish we had E, rather than C. A lot of this was slated for cleanup, but ATT labs released C before it was finished. D, according to K&R, was the debugged revision they were working on. E was going to be the reorganized version with more human readability and less cryptic things. So they told ATT Bell Labs they would be done with revision E. Well... Bell Labs published what they had working... revision C. And we all live with this legacy at some point.
Join our real-time social learning platform and learn together with your friends!