mej*_*jem 3 c operators c99 parameter-passing
我想在 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);
}
Run Code Online (Sandbox Code Playgroud)
有没有其他方法可以做到?我不想为每个运算符编写一个函数。
它可能看起来像这样:
int a = perform(something_cool_here, 3, 2);
小智 5
您可以使用 switch/case,例如:
int perform(char op,int a,int b)
{
switch (op)
{
case '+': return a+b;
case '-': return a-b;
default: return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
但是您仍然需要为每个操作符编写一些代码;你不会在 C 中免费获得任何东西。