-   Programming (
-   -   accessing functions using strings in runtime (

shyam_d_sundar 05-09-2005 12:49 AM

accessing functions using strings in runtime

I am designing a parser to read the input file for my code. In that, I use various commands and associate those commands with the relevant functions. Each time, i endup in adding a couple of lines like

return clear();
else if(strcmp(cmd,"copy")==0)
return copy();

All the member functions in that class are of same name as the commands. So, i need to automate this process in order to avoid the above statements. In otherwords, i want some thing like below ( function pointers? )

for(int i=0;i<num_func;i++)
return func[i]();

Please let me know.

Shyam :study:

itsme86 05-09-2005 11:05 PM

I think the only way is to create a lookup table:

itsme@dreams:~/C$ cat funcptr.c
#include <stdio.h>
#include <string.h>

void a(void)
  puts("Inside a");

void b(void)
  puts("Inside b");

int main(void)
    char *name;
    void (*func)(void);
  } list[] = {
              { "a", a },
              { "b", b },
              { NULL }
  int i;
  char input[20];

  for(;;)  // Loop forever
    printf("Enter a or b: ");

    fgets(input, sizeof(input), stdin);
    input[strlen(input) - 1] = '\0';

    for(i = 0;list[i].name;++i)  // Loop through list until NULL
      if(strcmp(list[i].name, input) == 0)

  return 0;


itsme@dreams:~/C$ ./funcptr
Enter a or b: a
Inside a
Enter a or b: b
Inside b
Enter a or b: a
Inside a
Enter a or b:

jonaskoelker 05-17-2005 05:48 PM

even better yet, use a hash table.

mehuljv 05-18-2005 08:02 AM

hi shyam,
cant u use a macro ??
#define CALL_FUNC(name) name()
where name is the copy, clear, or any cmd which u read from the file (provided it is valid command - function in ur case).
So u just read the word from the file and just do CALL_FUNC(name) which will call ur function. ........
M sorry u cant do in this manner... preprocessor will remove ur macro before compilation.


All times are GMT -5. The time now is 10:33 AM.