Thursday, November 11, 2010

Question 20.17

comp.lang.c FAQ list · Question 20.17

Q: Is there a way to switch on strings?


A: Not directly. Sometimes, it's appropriate to use a separate function to map strings to integer codes, and then switch on those:
#define CODE_APPLE 1
#define CODE_ORANGE 2
#define CODE_NONE 0

switch(classifyfunc(string)) {
 case CODE_APPLE:
  ...

 case CODE_ORANGE:
  ...

 case CODE_NONE:
  ...
}
where classifyfunc looks something like
static struct lookuptab {
 char *string;
 int code;
} tab[] = {
 {"apple", CODE_APPLE},
 {"orange", CODE_ORANGE},
};

classifyfunc(char *string)
{
 int i;
 for(i = 0; i < sizeof(tab) / sizeof(tab[0]); i++)
  if(strcmp(tab[i].string, string) == 0)
   return tab[i].code;

 return CODE_NONE;
}

Otherwise, of course, you can fall back on a conventional if/else chain:
if(strcmp(string, "apple") == 0) {
  ...
 } else if(strcmp(string, "orange") == 0) {
  ...
 }
(A macro like Streq() from question 17.3 can make these comparisons a bit more convenient.)
See also questions 10.1220.1620.18, and 20.29.
References: K&R1 Sec. 3.4 p. 55
K&R2 Sec. 3.4 p. 58
ISO Sec. 6.6.4.2
H&S Sec. 8.7 p. 248

No comments:

Post a Comment