#include #include #include typedef struct cmdtab { const char *name; void (*func)(); // Happy fun function pointers! } cmdtab; void do_moo() { printf("moooooo!\n"); } void do_quack() { printf("quaak!\n"); } /* Note the functions have to be declared BEFORE this structure!! */ cmdtab cmd[] = { /* Name Function */ { "MOO", do_moo }, { "QUACK", do_quack }, { NULL, } }; /* We now have an array of filled-out cmdtab structures, in cmd[] - note * the null at the end so we know where it ends.. */ int main(int argc, char **argv) { int i; if (argc < 2) { printf("usage: %s \n", argv[0]); exit(1); } /* Now we cycle through the structures, seeing if * argv[1] matches the name field. If it does, execute the * associated function pointer. Stop when we hit the NULL. */ for (i = 0; cmd[i].name; i++) { if (!strcmp(cmd[i].name, argv[1])) cmd[i].func(); } /* And that's it for today's demonstration of voodoo */ }