使用函数代替运算符

时间:2016-11-17 08:05:01

标签: c

所以我试图创建一个基于用户输入进行数学运算的程序,但是我遇到了一个问题,试图根据它们给出的数学运算符来设置它。

功能:

const operator(int val)
{
    if (val == 1)
    {
    return +;
    }
    if (val == 2)
    {
    return -;
    }
}

主代码看起来像这样

scanf("%d", val)
output = 4 operator(val) 2
printf("%d", output)

我是否可以使用变量类型代替运算符?如果没有,是否有办法使变量/函数引用定义的宏?

例如:

#define plus +

然后引用代码中的宏?

最后我知道如果每个输入的情况都可以,但是对于像

这样的东西来说这很难
output = 2 operator(val) 5 operator(val) 7 operator(val) 3 

这需要64个if语句我认为能使它工作。

感谢您的阅读,我的斗智尽头。

1 个答案:

答案 0 :(得分:5)

你可以做的是使用函数指针。

假设您将自己限制为整数并对此示例进行加/减:

int add(int a, int b)
{
    return a + b;
}

int subtract(int a, int b)
{
    return a - b;
}

// without typedef, the signature of get_operator would be really messy
typedef int (*arithmetic_func)(int,int);

arithmetic_func get_operator(int val)
{
    if (val == 1)
    {
        return &add;
    }
    if (val == 2)
    {
        return &subtract;
    }
    return NULL; // what to do if no function matches?
}

而不是output = 4 operator(val) 2你可以写:

output = get_operator(val)(4, 2)

会发生什么,get_operator(val)函数调用返回一个指向实际算术函数的函数指针。然后使用(4, 2)作为参数调用此实际算术函数。