A switch
statement can only evaluate an expression of an integral or enumeration type (or convertible to such a type), and the expression in each case
label must be a constant expression.
'SRAD'
is not a string literal. It's a character literal with an implementation-defined value of type int
. (This is a nearly useless language feature that I've seen used by mistake more than I've seen it used correctly.)
If you want to use C-style language features, avoiding things like C++'s std::string
, the equivalent would be an if
/else
chain:
if (strcmp(name, "SRAD") == 0) {
// ...
}
else if (strcmp(name, "DRAD") == 0) {
// ...
}
else {
// ...
}
If you use std::string
(which is advisable), the code would be similar, except that you can use ==
rather than strcmp
.
You could set up a data structure that lets compute a discrete value that you can then use in a switch
/case
statement, as R Sahu's answer suggests. This would save the overhead of potentially doing N string comparisons. In my opinion, that would be overkill for a simple case like this. If your actual code is larger and more complex, it's worth considering.
Or you might consider redesigning your data structure so that you store and test an enumeration value directly, and then get a string value from that enumeration value via a lookup table.