如何使用函数指针执行算术运算?

How do i perform arithmetic operations with function pointers?

所以..我明白如果我把(*ptr)作为函数f那么

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

所以现在我的问题是我必须读入 3 个整数。前 2 个是操作数,第三个是运算符,例如1 = add, 2 = subtract, 3 = multiply, 4 = divide。如果没有 if 或 switch 语句,我该怎么做。

我正在考虑两种可能的解决方案

  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

示例输入

1 2 1

1 2 2

1 2 3

1 2 4

样本输出

 3

-1

 2

 0 

我的代码:

#include <stdio.h>

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


//Function Prototypes
int add(int x, int y);


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

    arithFuncPtr ptr;

    //ptr points to the function add
    ptr = 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;
}

您可以将函数指针放在一个数组中。

#include <stdio.h>

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


//Function Prototypes
int add(int x, int y);
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[0] = add;
    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;
}

int add(int x, int y)
{
    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;
}