I'm trying to do switch with cases, but I want to use word instead of number or letter, e.g.
case 'quit': (...)
But I know that C doesn't support it.
Could you tell me how to use 'some word' in case?
I'm trying to do switch with cases, but I want to use word instead of number or letter, e.g.
case 'quit': (...)
But I know that C doesn't support it.
Could you tell me how to use 'some word' in case?
A switch
statement is no more than some optimization to choose among one of a number of options. Any switch statement can be implement as an if...then...else if...
statement.
The optimization in C is for integers and it cannot handle strings
A witch statement for strings would thus be an if...then...else if...
statement using strcmp
, e.g.
if (strcmp(a,"hello")==0) {
//case "hello"
}
else if (strcmp(a,"world")==0) {
// case "world"
}
else {
// default
}
One difference betwee a switch
statement and an if..then..else
statement is that the latter does not know "fall thru" and it cannot be simulated unless using goto
(which is discouraged).
The comments to your question also suggest more advanced methods than brute force string-compare. All those methods try to use some unique characteristic of your string to translate into some number on which a switch
can be implemented.