??回调函数就是?个通过函数指针调?的函数。
? 先让我们引入例子:
? 这是一个我们自制模拟计算器计算两个整数加减乘除的代码:
//使?回调函数改造前
#include <stdio.h>
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
int mul(int a, int b)
{
return a * b;
}
int div(int a, int b)
{
return a / b;
}
int main()
{
int x, y;
int input = 1;
int ret = 0;
do
{
printf("******************
printf(" 1:add
printf(" 3:mul
printf("******************
printf("请选择:");
scanf("%d", &input);
switch (input)
{
case 1:
printf("输?操作数:");
scanf("%d %d", &x, &y)
ret = add(x, y);
printf("ret = %d\n", r
break;
case 2:
printf("输?操作数:");
scanf("%d %d", &x, &y)
ret = sub(x, y);
printf("ret = %d\n", r
break;
case 3:
printf("输?操作数:");
scanf("%d %d", &x, &y)
ret = mul(x, y);
printf("ret = %d\n", r
break;
case 4:
printf("输?操作数:");
scanf("%d %d", &x, &y)
ret = div(x, y);
printf("ret = %d\n", r
break;
case 0:
printf("退出程序\n");
break;
default:
printf("选择错误\n");
break;
}
} while (input);
return 0; }
? 我们发现在每一个case的后面都有着一堆相似重复的代码,这些代码会增加计算机的负担,对此,我们可以通过回调函数来对代码进行优化。
//使?回到函数改造后 #include <stdio.h>
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
int mul(int a, int b)
{
return a * b;
}
int div(int a, int b)
{
return a / b;
}
void calc(int(*pf)(int, int))
{
int ret = 0;
int x, y;
printf("输?操作数:");
scanf("%d %d", &x, &y);
ret = pf(x, y);
printf("ret = %d\n", ret);
}
int main()
{
int input = 1;
do
{
printf("******************
printf(" 1:add
printf(" 3:mul
printf("******************
printf("请选择:");
scanf("%d", &input);
switch (input)
{
case 1:
calc(add);
break;
case 2:
calc(sub);
break;
case 3:
calc(mul);
break;
case 4:
calc(div);
break;
case 0:
printf("退出程序\n");
break;
default:
printf("选择错误\n");
break;
}
} while (input);
return 0;}