# c - How do i perform arithmetic operations with function pointers?

So..I understand that if i take(`*ptr`) as some function f then

``res = (*ptr)(a,b) is the same as res = f(a,b).``

So now my problem is that I have to read in 3 integers. First 2 are the operands, third is the operator e.g. `1 = add, 2 = subtract, 3 = multiply, 4 = divide`. How do I do it without if or switch statements.

I was thinking of two possible solutions

1. create 4 pointers and deference each pointer to an arithmetic operation, but with that I still have to do some sort of input

validation which would require if or switch statements

2. This isn't really a solution but the basic idea would probably by like. if c = operator then I can somehow do something like res =

(*ptrc)(a,b) but I don't think there's such a syntax for C

Sample input

``1 2 11 2 21 2 31 2 4``

Sample Output

`` 3-120``

My Code :

``#include <stdio.h>//Datatype Declarationstypedef int (*arithFuncPtr)(int, int);//Function Prototypesint add(int x, int y);int main(){int a, b, optype, res;arithFuncPtr ptr;//ptr points to the function addptr = add;scanf("%i %i", &a, &b);res = (*ptr)(a, b);printf("%i\n", res);return 0;}int add(int x, int y){return x+y;}``

You may put you functions pointers in an array.

``````#include <stdio.h>

//Datatype Declarations
typedef int (*arithFuncPtr)(int, int);

//Function Prototypes
int sub(int x, int y);
int mul(int x, int y);
int div(int x, int y);

int main()
{
int a, b, optype, res;

arithFuncPtr ptr[4];

//ptr points to the function
ptr[1] = sub;
ptr[2] = mul;
ptr[3] = div;

scanf("%i %i %i", &a, &b, &optype);

res = (ptr[optype - 1])(a, b);

printf("%i\n", res);

return 0;
}

{
return x+y;
}

int sub(int x, int y)
{
return x-y;
}

int mul(int x, int y)
{
return x*y;
}

int div(int x, int y)
{
return x/y;
}
``````