C/C++ Arena

Step 3 of 6

A dispatch table

An array of structs pairing a name with a function replaces a long if/else if chain. Adding a command becomes one line in the table, and the lookup code never changes:

typedef struct {
    const char *name;
    int (*fn)(int, int);
} Command;

static const Command commands[] = {
    {"add", add},
    {"sub", sub},
};

Interpreters, command-line tools, network protocol handlers and state machines are all built this way.

Your turn: the program reads lines like add 2 3 until end of input. Look up the command in the table and print the result, or unknown CMD if it isn't there. Add a mul command to the table as well.

Previous: typedef and passing callbacks Next: Sorting with qsort