Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!timbuk!shamash!bls From: bls@u02.svl.cdc.com (Brian Scearce) Newsgroups: comp.lang.c Subject: Re: strings as functions Keywords: strings pointers functions Message-ID: <29668@shamash.cdc.com> Date: 7 Jan 91 22:21:47 GMT References: Sender: usenet@shamash.cdc.com Lines: 49 mpapp@ (Mike Papper) writes: >Is there a way to use a string value as the name of a function? It depends on what you mean. If, at compile time, you can make up a table, then it is pretty easy: #include #define MAXLEN 100 void first(), second(), third(), last(); struct mapping { char *name; void (*func)(); }; main() { void first(), second(), third(), last(); static struct mapping list[] = { "first", first, "second", second, "third", third, "last", last, NULL, NULL }; char buf[MAXLEN]; int i; while (fgets(buf, MAXLEN, stdin) != NULL) { buf[strlen(buf)-1] = 0; /* Get rid of newline */ for (i = 0; list[i].name; i++) if (strcmp(list[i].name, buf) == 0) (*list[i].func)(); } } void first() { printf("First function\n"); } void second() { printf("Second function\n"); } void third() { printf("Third function\n"); } void last() { printf("Last function\n"); } -- Brian Scearce (bls@robin.svl.cdc.com -or- robin!bls@shamash.cdc.com) "How do you explain the vast discrepancy between your testimony and my client's?" "He has perjured himself." "Objection!" "I am under oath. I was there. He *is* lying." Any opinions expressed herein do not necessarily reflect CDC corporate policy.