50. Event-Based Triggers Using Function Pointer Array

#include <stdio.h>

void on_button() {
    printf("Button Pressed");
}
void on_timer() {
    printf("Timer Expired");
}
void on_uart() {
    printf("UART Received");
}
void on_power() {
    printf("Power On");
}
void on_error() {
    printf("Error Detected");
}

void handle_event(int event_code) {
    // Array of function pointers to event handlers
    void (*event_table[5])() = {
        on_button,
        on_timer,
        on_uart,
        on_power,
        on_error
    };

    if (event_code >= 0 && event_code < 5) {
        event_table[event_code]();  // Call the corresponding function
    } else {
        printf("Unhandled Event");
    }
}

int main() {
    int event;
    scanf("%d", &event);
    handle_event(event);
    return 0;
}

In embedded firmware, interrupts and peripheral triggers are often mapped to handler functions, which are dynamically assigned in a lookup table (ISR vector, event loop).

This structure replicates that behavior using:

  • Array of function pointers
  • Indexing to dispatch functions
  • Efficient, readable event-driven logic

Solution Logic:

  • Define an array of 5 function pointers
  • Each pointer refers to a handler function
  • On receiving an event code, check if valid
  • If valid → call handler
  • Else → print "Unhandled Event"
     

Alternate Solution

typedef void (*EventFunc)();

void handle_event(int code) {
    EventFunc table[] = { on_button, on_timer, on_uart, on_power, on_error };

    if (code >= 0 && code < 5)
        table[code]();
    else
        printf("Unhandled Event");
}


 

Loading...

Input

0

Expected Output

Button Pressed