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.
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)
The right answer in many languages is an associative container of some kind; std::map
in C++, for example. There's a C implementation of an associative array in Glib: see here. There are other libraries that have their own.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With