All submissions

Event-Based Triggers Using Function Pointer Array

Code

#include <stdio.h>

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

void trigger_event(int code) {
    void (*handlers[5])() = { on_button, on_timer, on_uart, on_power, on_error };

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

int main() {
    int code;
    scanf("%d", &code);
    trigger_event(code);
    return 0;
}

Solving Approach

 

 

 

Loading...

Input

0

Expected Output

Button Pressed