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

标签 c math function-pointers arithmetic-expressions

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

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

所以现在我的问题是我必须读入 3 个整数。前 2 个是操作数,第三个是运算符,例如1 = 加法,2 = 减法,3 = 乘法,4 = 除法。如果没有 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;
}  

关于c - 如何使用函数指针执行算术运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32390328/

相关文章:

c - C中函数指针数组的表达

c++ - 为什么不能将函数指针与没有显式 & 函数名称的模板函数进行比较?

c - 将结构成员传递给 C 中同一结构中的函数指针

c - mysqlclient.lib 的来源在哪里?

algorithm - 简化表达式 k/m%n

javascript - 为什么 0.86%1 不是零而是 0.86,因为 0.86/1 的余数为 0?

java - 反向 Elo 算法

c - SSE2 有符号整数溢出未定义吗?

c - 如何将 C 中的多行宏与行尾的注释结合起来

c - 如何在不取消引用的情况下确定指向数据的大小?