gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:01:06 24 4
gpt4 key购买 nike

我想在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com