C语言的一个函数指针示例
#include<stdio.h>
typedef int(*Calc)(int a, int b);
int Add(int a, int b)
{
int result = a + b;
return result;
}
int Sub(int a, int b)
{
int result = a - b;
return result;
}
int main()
{
int x = 100;
int y = 200;
int z = 0;
// 原本C语言的写法
z = Add(x, y);
printf(" % d + % d = % d\n", x, y, z);
z = Sub(x, y);
printf(" % d - % d = % d\n", x, y, z);
// 改为新的形式
Calc funcPoint1 = &Add;
Calc funcPoint2 = ⋐
z = funcPoint1(x, y);
printf(" % d + % d = % d\n", x, y, z);
z = funcPoint2(x, y);
printf(" % d - % d = % d\n", x, y, z);
return 0;
}
输出样例: