Reputation: 5
How to convert a word from the string and use it as a function name?
For example:
//Given string:
char[] givenString = "myGoal 1,2,3,4";
//Function:
void myGoal()
{
...
}
I want to extract a word (index 0) "myGoal" from givenString, than use it as a function.
I was thinking to use a control flow: else-if or switch:
ex.:
else-if:
#include <string.h>
#include <stdio.h>
char[] word = "myGoal";
if(strcmp(word, givenString[0])
{
myGoal();
}
or switch:
#include <stdio.h>
char[] word = givenString[0];
switch(word){
case "myGoal":
myGoal();
break;
}
The problem is that I have a large number of functions, so using of control flow looks not elegant.
I`m sure there must be a nice solution for my code.
Thank you!
Upvotes: 0
Views: 262
Reputation: 409356
You need some way to map from the string to the function.
If you have multiple strings and functions, an array of structures containing the string and a pointer to the function is a common way to solve the problem:
struct map_struct
{
const char *string;
void (*function)(void);
};
struct map_struct map[] = {
{ "myGoal", &myGoal },
// TODO: Other strings and functions here...
};
Then you iterate (loop) over the array trying to find the corresponding entry, and call the function:
(*map[some_valid_index].function)();
Note that the method above works find if all functions take the exact same arguments and return the exact type.
If you have different functions taking different arguments, then you either need multiple map structure and array, use a chain of if
/else
to call the functions explicitly with the correct arguments.
Or you can use a "generic" pointer to pass structures containing the actual arguments (like many C thread libraries work).
Or if all the data you pass are of the same type, then you could use an array (possibly dynamically allocated) and pass a pointer to the first element, together with the number of elements.
Upvotes: 1