Ganesh Kundapur <gk*******@yahoo.com> wrote in message news:<3F**************@yahoo.com>...
Hi all,
suppose i have 100 functions such as f1, f2,...f100 in a single
file including main. If i pass arguement to main such as
$a.out f1
main should call appropriate functions. I can do this using switch
statement, but if i have 1000 functions, then i have to write 1000 cases
OR i can use pointer to functions. I am passing string to main, how to
map this string to function efficiently.
You're going to have to implement a lookup table of some sort. If all
of the called functions have the same return type and number of
parameters, you could do something like the following (probably not
the best way of doing it, but I'm doing this off the top of my head):
void f1 (void) {...}
void f2 (void) {...}
void f3 (void) {...}
....
void f100 (void) {...}
struct fassoc {
char name[5]; /* long as longest function name + 1 */
void (*fptr)(void); /* pointer to function */
};
struct fassoc fassoc_table[100] =
{ {"f1", f1}, {"f2", f2}, {"f3", f3}, ..., {"f100", f100} };
void call_func_by_name (char *name)
{
int i;
for (i = 0; i < 100; i++)
{
if (strcmp (name, fassoc_table[i].name) == 0)
{
fassoc_table[i].fptr ();
break;
}
}
}
int main (int argc, char **argv)
{
if (argc == 2)
{
call_func_by_name (argv[1]);
}
return 0;
}
If the functions have different return types or take different numbers
of parameters, then things get a bit trickier. You'd still need a
lookup table, but now you'd need to accomodate several types of
function pointers, and I'm not sure if you could initialize it like
above (you'd probably have to call a function at program startup to
set up the lookup table).