I am trying to build a parser to a given input, there are 8 possible commands. So I figured that instead of using the ugly technique of a case switch
block like that:
switch(command)
case cmd1:
.... /*call a function that do cmd1*/
case cmd2
..../*call a function that do cmd2*/
I will define in a header an array of structs, each one contains the name of the function, and a pointer to a function:
typedef struct command_info
{
char *name;
void (*func)(int)
};
command_info command_table[] = {{"func1", &func1}, {"func2", &func2} }
So that I can switch to the more elegant:
int i;
for(i = 0; i < COMMAND_TABLE_LENGTH; i++)
if(!strcmp(command_table[i].name, command))
command_table[i].func(2);
My only problem is, that the functions have different parameters (all return void). This is not a problem for me since I can check if the function is func1
or func2
search for one int argument for example, and if it is func3
or func4
search for two (still more compact than case switch
). But the function pointer only points to a function with a certain type and amount of arguments. How can I make a universal pointer that can point to any function?