56. Function Pointer Dispatch Table

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
int divide(int a, int b) { return a / b; }

typedef int (*PFI_I_I)(int, int);

static PFI_I_I fnptr_arr[] = {
    add,sub,mul,divide
};

int execute_command(int a, int b, int cmd) {
    // Your logic here using function pointer array
    return fnptr_arr[cmd](a, b);
}

int main() {
    int a, b, cmd;
    scanf("%d %d %d", &a, &b, &cmd);

    int result = execute_command(a, b, cmd);
    printf("%d\n", result);

    return 0;
}

Solving Approach

Use typedef to simplify the naming and syntax. Function pointer indices are the same as the order of the given functions.

 

 

 

Was this helpful?
Upvote
Downvote