Originally Posted by
laserlight
You can map strings to function pointers such that you can search for the string, obtain the function pointer, then call the function. This way, you just need to modify the contents of the data structure instead of adding another branch to an if-else chain.
A very basic example of this would be:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void myHello(void);
void myGoodBye(void);
int main(void){
//create framework for function table
struct myFunctionTable{
char *myName;
void (*myFunction)(void);
};
//make function table, aka array
myFunctionTable FunctionTable[]={{"Hello", &myHello}, {"GoodBye", &myGoodBye}};
char myAnswer[10];
printf("Which function to run?");
scanf("%s", myAnswer);
//find and run function
for(int i = 0; i < (sizeof(FunctionTable) / sizeof(myFunctionTable));i++){
if(strcmp(FunctionTable[i].myName,myAnswer)==0){
FunctionTable[i].myFunction ();
break;
}
}
getchar();
getchar();
return (0);
}
//Implement functions
void myHello(void){
printf("Hello World\n");
}
void myGoodBye(void){
printf("GoodBye World\n");
}