On 4 Apr 2000, at 11:51, Jerry Eckert wrote:
> Hi Folks,
>
> I hope it's not inappropriate to ask a C language question here.
>
> Is there a more elegant way to do the equivalent of a switch statement for a
> character string value than a chain of if (strcmp())... else if
> (strcmp())... else if.... ?
>
> What I tried to do was
>
> switch (char-var) {
> case "string1":
> ...
> }
>
> Eventually I figured out character strings aren't a data type in C. Sigh...
In C, the switch statement must use only integer arguments.
Specifically, the argument of the switch is an expression, and the target
of case must be a constant. There are some more elegant solutions.
Here is a quick hack. Set up your comparison strings in a table. Just
loop through the table until you get a match. If you have a match, set a
selector which you can use in a switch statement later on if you wish.
Another parsing technique is to switch on the first (or any arbitrary)
character of the string if you have a large number of strings or a symbol
table whatever. Here is a short hack to show the table technique. I used
a struct in this case, but you could easily use an array of strings. You
can even order them so you can do a binary search.
struct {
const char *s;
int sel;
} foo[] = {
{ "string1", 1 },
{ "string2", 7 },
{ NULL, 3 }
};
--- code:
char *istring; /* input string */
for(i=0;foo[i].s;i++) {
if (strcmp(istring, foo[i].s) == 0) {
sel = foo[i].selector;
break;
}
}
The above code is a quick hack, bu
Jerry Feldman <[EMAIL PROTECTED]>
Associate Director
Boston Linux and Unix user group
http://www.blu.org
**********************************************************
To unsubscribe from this list, send mail to
[EMAIL PROTECTED] with the following text in the
*body* (*not* the subject line) of the letter:
unsubscribe gnhlug
**********************************************************