accessing functions using strings in runtime
hi,
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 if(strcmp(cmd,"clear")==0) 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++) if(strcmp(cmd,func_name[i])==0) return func[i](); Please let me know. Regards, Shyam :study: |
I think the only way is to create a lookup table:
Code:
itsme@dreams:~/C$ cat funcptr.c Code:
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: |
even better yet, use a hash table.
|
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. Bye Mehul |
All times are GMT -5. The time now is 02:43 AM. |