All submissions

Function Pointer Dispatch Table

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; }

int execute_command(int a, int b, int cmd) {
    // Your logic here using function pointer array
    int (*operations[])(int, int) = {add, sub, mul, divide};

    return operations[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", result);

    return 0;
}

Solving Approach

/*
Questions:
- a & b(guranteed to be non-zero) are valid integers
- cmd range is always between [0,3]?
- Function ptr array static / global?
- Return type is int
- no if else / switch

Plan:
- Define operation func
- Array of function pointers
- Dispatch via Command code in exe-cmd
- Return the result
- Test in main


*/

 

 

Loading...

Input

10 5 0

Expected Output

15