回调函数的意思:创建一个函数1,函数1的内部需要调用函数2,就把函数2指针当中函数1的形参
回调函数的作用:功能比一个单一的函数更加强大。通过函数的参数不一样,实现的功能也不一样。像一个中间代理。
相同的代码出现了多份,就显得冗余。就需要回调函数。
calc(Add)函数名代表的是函数的地址
回调函数是通过其他函数来实现的,不是他自己回调。
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int Add(int x, int y)
{
return x + y;
}
int Sub(int x, int y)
{
return x - y;
}
int Mul(int x, int y)
{
return x * y;
}
int Div(int x, int y)//只适用于整数
{
return x / y;
}
void calc(int (*pf)(int, int))
{
int x = 0;
int y = 0;
int ret = 0;
printf("请输入两个操作数:");
scanf("%d %d", &x, &y);
ret = pf(x, y);
printf("%d\n", ret);
}
void menu()
{
printf("----------计算器--------\n");
printf("----1.加法 2.减法----\n");
printf("----3.乘法 4.除法----\n");
printf("----0.退出 ----\n");
printf("------------------------\n");
}
int main()
{
int input = 0;
do
{
menu();
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;
default:
input = 0;
break;
}
} while (input);
return 0;
}