c++ - Why can't the switch statement be applied to strings? - Stack Overflow

PHOTO EMBED

Tue Feb 06 2024 13:03:33 GMT+0000 (Coordinated Universal Time)

Saved by @tarangit #cpp #switch_alternative_for #string

enum string_code {
    eFred,
    eBarney,
    eWilma,
    eBetty,
    ...
};

string_code hashit (std::string const& inString) {
    if (inString == "Fred") return eFred;
    if (inString == "Barney") return eBarney;
    ...
}

void foo() {
    switch (hashit(stringValue)) {
    case eFred:
        ...
    case eBarney:
        ...
    }
}
content_copyCOPY

Switch alternative for strings

https://stackoverflow.com/questions/650162/why-cant-the-switch-statement-be-applied-to-strings