5

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.

Community
  • 1
  • 1
Frank Vilea
  • 8,323
  • 20
  • 65
  • 86

3 Answers3

5

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)

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    The C standard library comes with a `bsearch()` function that can be used for the purpose of finding a string in an ordered array by passing strcmp as the comparator. – pmdj May 07 '12 at 11:11
  • I think that this approach is the best because it feels "clean". I posted a solution here: http://pastebin.com/21jpeLkh – Frank Vilea May 07 '12 at 11:30
  • I would be glad if you could have a look and tell me if this is what you had in mind. Thanks again! – Frank Vilea May 07 '12 at 11:31
  • My other idea was to simply encode all the currencies as numerical values in the db. This of course only works for this specific case. – Frank Vilea May 07 '12 at 11:32
  • @user1288263 Yes, your pastebin source is precisely what I had in mind. In the specific case of currencies you can use (yet) another trick - think of a 3-letter currency code as an *integer in base-26 notation*. You can write a function to convert from base-26, and define integer preprocessor constants for converted codes of currencies that you would like to process. – Sergey Kalinichenko May 07 '12 at 11:45
1

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.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
1

I would suggest to use an if statements for this case with strcmp function.

besworland
  • 747
  • 2
  • 7
  • 17