strings as functions

Brian Scearce bls at u02.svl.cdc.com
Tue Jan 8 09:21:47 AEST 1991


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 <stdio.h>
#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 at robin.svl.cdc.com  -or-  robin!bls at 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.



More information about the Comp.lang.c mailing list