Event-Based Triggers Using Function Pointer Array

Code

#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");
}

// Write your event dispatcher logic here
void handle_event(int event_code) {
    // Your logic
    void (*events[5])()= {on_button,on_timer,on_uart,on_power,on_error};

    if(event_code >= 0 && event_code < 5) {
        events[event_code]();
    } else {
        printf("Unhandled Event");
    }
}

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

Solving Approach

  • Store event handler functions in an array of function pointers.
  • Use the event code as the index to call the right handler.
  • If the code is invalid (not 0–4), print "Unhandled Event".

 

 

Upvote
Downvote
Loading...

Input

0

Expected Output

Button Pressed