在使用指向函数的指针调用函数时,可以使用两种形式:
定义:int (*fun)(int a,int b);
赋值:fun = fun1;
调用:fun(a,b);或者(*fun)(a,b);均可。
下面是测试程序:(Visual Studio 2013)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int add(int x, int y)
{
return x + y;
}
int minus(int x, int y)
{
return x - y;
}
int compute(int x, int y, int(*f)(int x, int y))
{
//return f(x, y);
return (*f)(x, y);
//使用上述两种情况均可。
}
int main()
{
int x, y;
char z;
int n;
while (1)
{
printf("input:");
scanf("%d%c%d", &x, &z, &y);
switch (z)
{
case '+':
n = compute(x, y, add);
break;
case '-':
n = compute(x, y, minus);
break;
default:
break;
}
printf("%d\n", n);
}
return 0;
}
测试结果: