LearnFrenzy
Sign in Take a free test

Typedef · typedef Programs · Question 6

Event dispatcher with a table of typedef'd handlers in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Map event names to handler functions in a table and dispatch events by name, reporting unknown events.

Solution
main.c
#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;
}

Output Verified by compiling and running

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links