C++ Switch Statement Using Strings

This is an update of a post that originally appeared onĀ May 13, 2015.

Readers sometimes ask me the same question often enough that I feel compelled to provide the answer on my blog so that everyone has the benefit of seeing it. C++ does have a switch statement, but you need to use a numeric value with it as described in my book, C++ All-In-One for Dummies, 4th Edition (see page 295 for details). A number of C# developers who are also learning to use C++ have asked me about using strings in the switch statement, which is clearly impossible without some fancy programming technique.

Fortunately, I have found a method for implementing switches using strings on CodeGuru. As the author states, it’s not a perfect solution and you may not find it works for you, but it is an ingenious coding technique and you should at least look at it. It’s better than saying the goal isn’t achievable using any means. To get a better idea of the methods other coders have used to overcome this problem, check out online discussions, such as Why switch statement cannot be applied on strings?.

Something I haven’t been asked about very much, but is really important, is the use of other approaches when working with switches, such as expressions. The C++ switch..case Statement article shows how to use expressions with switch statements, while Switch Statement in C/C++ explores some interesting uses of expressions with switches in more detail. The switch statement documentation discusses upcoming changes for C++ 23, but these changes currently don’t appear in my book.

Of course, I’m always on the lookout for other good solutions to reader problems. If you have another solution to this issue of using strings with the C++ switch statement, please contact me at [email protected]. I always want to keep the door open to an even more innovative solutions. In the meantime, keep those e-mails coming!