-1

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?

connie
  • 1
  • 1
  • 1
    Either calculate a unique ordinal to use in the case-statements or use if-statements. – Lasse V. Karlsen Dec 02 '17 at 17:41
  • You can't, but you could test the word against an array of key words, and use the index of a match as the switch case. Or, you could have words with a unique initial and use that for the switch case. – Weather Vane Dec 02 '17 at 17:41
  • Chek [this](https://stackoverflow.com/questions/4014827/best-way-to-switch-on-a-string-in-c) out. – vitruvius Dec 02 '17 at 17:42

1 Answers1

1

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.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41