wrote:
>
[ snip ]
>
> /* Approach #2 */
> void do(char* input) {
> char* commands[] = {"foo", "bar", "baz"};
> enum { FOO = 0, BAR, BAZ, MAX };
>
> int cmd = 0;
> while(cmd < MAX) if(strcmp(commands[cmd++], input)==0) break;
>
> switch(cmd) {
> case FOO: do_foo(); break;
> case BAR: do_bar(); break;
> case BAZ: do_baz(); break;
> default: do_wtf(); break;
> }
> }
This approach seems the easiest to maintain
of the two. A couple of suggestions -
If the number of commands isn't too many,
I put them in the list sorted, and use
a less than or equal to for the comparison.
OR
If some of the commands are more heavily used
over the other commands, then put them
in the beginning of the `commands' array.
I'd also use `(sizeof(commands) / sizeof(commands[0]))'
instead of `MAX', and make the enum a "type" -
enum { FOO = 0, BAR, BAZ, } cmd;
This way (e.g. gcc) will warn if a new item is added
to the `commands' and the enum type, but is not
added to the switch statement. Kinda a minor point, though.
---
If you're _really_ feeling crazy, you could marry
the command string and it's function pointer handler
into a structure, and build an array of those.
Now you can eliminate the enum (since it's only
acting as a function pointer index anyway, and
a possibly long switch statement. This, of
course, assumes all of the handlers can have
the same or compatible prototype (which your example does).
HTH,
Stephen