Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C strings in a switch statement [duplicate]

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.

like image 960
Frank Vilea Avatar asked May 07 '12 11:05

Frank Vilea


2 Answers

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)

like image 89
Sergey Kalinichenko Avatar answered Sep 29 '22 07:09

Sergey Kalinichenko


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.

like image 24
Ernest Friedman-Hill Avatar answered Sep 29 '22 06:09

Ernest Friedman-Hill