Question 6
Back to Exercise
Map event names to handler functions in a table and dispatch events by name, reporting unknown events.
Solution
#include <stdio.h>
#include <string.h>
typedef void (*EventHandler)(int value);
typedef struct {
const char *name;
EventHandler handler;
} Event;
static void on_click(int v) { printf("click at x=%d\n", v); }
static void on_key(int v) { printf("key '%c'\n", v); }
static const Event events[] = {{"click", on_click}, {"key", on_key}};
void dispatch(const char *name, int value) {
for (size_t i = 0; i < sizeof events / sizeof events[0]; i++)
if (strcmp(events[i].name, name) == 0) {
events[i].handler(value);
return;
}
printf("no handler for %s\n", name);
}
int main(void) {
dispatch("key", 'q');
dispatch("click", 42);
dispatch("scroll", 0);
return 0;
}
key 'q' click at x=42 no handler for scroll
Two typedefs – one for the handler signature, one for the table row – turn the dispatcher into a short loop. GUI toolkits and game engines register callbacks the same way.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!