Reputation: 347
I've come across some C syntax that I've never seen before:
static struct {
char *name;
void (*f)(int a, int b, int c);
} commands[] = {
{ "cmd1", func1 },
{ "cmd2", func2 },
{ "cmd3", func3 },
};
This pertains to a command parser that matches a user input command to one of the respective functions like this:
for (int i = 0; i < N; ++i) {
if (strcmp(args[0], commands[i].name) == 0) {
(commands[i].f)(a, b, c);
return;
}
}
I can't even search google for help because I don't know what this sort of structure is called, and it seems somewhat esoteric.
What I want to do is create more of these structs, then put the loop into a separate function and generalize it, so that I can pass the function different structs depending on certain conditions. However I can't figure out how to assign the structs to a variable and pass them to a function.
Upvotes: 2
Views: 113
Reputation:
What I want to do is create more of these structs, then put the loop into a separate function and generalize it
Then you probably want to give a name (tag) to the struct, like this:
struct command {
const char *name; // notice the `const', by the way!
void (*f)(int a, int b, int c);
};
and isolate the type definition and the variable declaration:
struct command commands[] = {
{ "cmd1", func1 },
{ "cmd2", func2 },
{ "cmd3", func3 },
};
The trick is that the struct
keyword creates a type immediately (as soon as the closing brace in the structure definition is encountered), so you don't have to have a separate struct
declaration and the definition of a variable of that struct type, these can be merged -- that's what the code you posted does.
Upvotes: 3
Reputation: 753475
The member void (*f)(int a, int b, int c);
is a pointer to a function that returns void
and takes 3 int
arguments.
Note that you cannot create any other variables of this type because the structure has no tag. You also can't pass this structure to any other function for the same reason.
typedef struct Command
{
char *name;
void (*f)(int a, int b, int c);
} Command;
static Command commands[] =
{
{ "cmd1", func1 },
{ "cmd2", func2 },
{ "cmd3", func3 },
};
The type Command
or struct Command
can now be used elsewhere if the type definition is placed in a suitable location (at file scope, or in a header).
Upvotes: 2