C strings in a switch statement

c, switch-statement

Solution

One way would be defining an array of C strings, and use it as a definition of your ordering:

const char *currencies[] = {"USD", "GBP", "EUR"};

Now you can search `currencies` for your string, and use its index in a switch statement.

You can get fancy and - sort your strings, and use `bsearch` to find the index in `O(LogN)`

Problem

Possible Duplicate: best way to switch on a string in C What is the general approach that is being used for strings (c character arrays) together with a switch statement? I'm querying my database for currencies that are stored as ``` "USD" "EUR" "GBP" ``` and so on. Coming from a PHP background, I would simply do: ``` switch ($string) { case "USD": return "$"; break; case "EUR": return "€"; break; case "GBP": return "£"; break; default: return "$"; } ``` In C the case-value has to be an integer. How would I go about implementing something like that in C? Will I end up writing lots of strcmp's in a huge if/else block? Please also note that I cannot simply compare the first characters of the currencies as some (not in this example though) start with the same character.

Original source

Related problems