c - 在 C99 中将运算符作为参数传递

标签 c operators parameter-passing c99

我想在 C99 中将运算符作为参数传递。 我的解决方案是这样的:

int add(int l, int r)
{
    return l + r;
}

int sub(int l, int r)
{
    return l - r;
}

// ... long list of operator functions

int perform(int (*f)(int, int), int left, int right)
{
    return f(left, right);
}

int main(void)
{
    int a = perform(&add, 3, 2);
}

还有其他方法吗?我不想为每个运算符都编写一个函数。

它可能看起来像这样:

int a = perform(something_cool_here, 3, 2);

最佳答案

你可以使用 switch/case,例如:

int perform(char op,int a,int b)
{
    switch (op)
    {
    case '+': return a+b;
    case '-': return a-b;
    default: return 0;
    }
}

但是您仍然需要为每个运算符编写一些代码;你不会在 C 中免费得到任何东西。

关于c - 在 C99 中将运算符作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36049647/

相关文章:

c - 将文本文件逐行读入c中的结构

c - 你如何使用 VisualDSP++ 在 C 语言中舍入 float ?

angular - 如何为 Angular 组件提供自定义对象?

powershell - 类似 PowerShell 的运算符支持哪些模式?

vb.net - VB 传递参数值 ByRef 在方法退出之前不会改变值?

c# - 在两个窗体之间传递值

c - 使用系统调用 mount() 以只读方式重新挂载 ext4 文件系统

c - C 中动态帐户连接的最佳解决方案?

c++ - 您使用 : and, 或不使用哪些 C++ 逻辑运算符以及同类或 C 风格的运算符?为什么?

c++ - C++中的运算符==顺序