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
    // create an array of pointers_to_function

    int(*arr[4])(int,int)={add,sub,mul,divide};
    int result;
    result=arr[cmd](a,b);
    return result;
}

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

syntax to declare the array of pointers is important 

  1. data_type* arr_name[size]={mem_add1,mem_add2,mem_add3 ....};

now for declaring array of pointers , which point to functions having return type and arguments. 

The syntax is important :   return_type_of_function (*array_name[size_of_array])(argument_data_types)={function name....};

Ex: int (*arr[4])(char,int) ={fun1,fun2,fun3,fun4}; 

return type of 4 functions is int and each function has arguments of type-char, int ; 

 

 

 

Upvote
Downvote
Loading...

Input

10 5 0

Expected Output

15