Why the switch statement cannot be applied on strings?

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.

Leave a Comment