Anonymous structs

On multiple occasions I have wanted to create a command-line interface with different subcommands. Recently I have been experimenting with writing an IRC bot that handles different commands passed to it.

I used the following to create an array of IRC commands (called "handlers") that contains the command that needs to be matched on and the function to call.

struct {
	char *cmd;
	void (*fn)(struct irc_message *);
} handlers[] = {
	{ "001", handle_001 },
	{ "PING", handle_ping },
};

Once a command is received we can find the right function to call in the following manner:

struct irc_message *msg = …;
unsigned i;
for (i = 0; i < sizeof(handlers) / sizeof(*handlers); ++i) {
	if (strcmp(command, handlers[i].cmd) == 0) {
		handlers[i].fn(msg);
		break;
	}
}

Aside: if you don't like strcmp(), there's strncmp() that can be called as with strlen(command) as the third argument.

https://git.sr.ht/~laumann/bot/tree/master/item/bot.c