回调函数
回调函数就是⼀个通过函数指针调⽤的函数。如果你把函数的指针(地址)作为参数传递给另⼀个函数,当这个指针被⽤来调⽤其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现⽅直接调⽤,⽽是在特定的事件或条件发⽣时由另外的⼀⽅调⽤的,⽤于对该事件或条件进⾏响应。
我们看两个回调的例子。
例1:使用回调函数实现计算器
#include <stdio.h>
#include <stdlib.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 (*pfunc)(int,int))
{
int x = 0;
int y = 0;
scanf("%d%d",&x,&y);
printf("result = %d\n",pfunc(x,y));
}
int main()
{
int input = 0;
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:
break;
}
}
例2:使用回调函数模拟实现 qsort (采用冒泡排序的方式)
#include <stdio.h>
#include <stdlib.h>
// 根据不同的数据类型,自己编写不同的回调函数,进行数据比较
// n1 > n2,返回值 >0
// n1 = n2,返回值 =0
// n1 = n2,返回值 <0
int int_cmp(const void* n1, const void* n2) {
return *(int*)n1 - *(int*)n2;
}
// 按字节进行数据交换
void swap(void* n1, void* n2, int width) {
int i = 0;
// 非法输入
if (n1 == NULL || n2 == NULL) {
exit(1);
}
for (; i < width; i++) {
char tmp = *((char*)n1+i);
*((char*)n1 + i) = *((char*)n2 + i);
*((char*)n2 + i) = tmp;
}
}
// arr : 待排序数组首元素
// len : 数组长度
// width : 数组元素宽度(元素类型所占字节数)
// int (*cmp)(void*, void*) : 一个参数为(void*, void*) 返回值为 int 的函数指针
void bubble_sqort(void* arr, int len, int width, int(*cmp)(void*, void*)) {
int i = 0;
// 进行冒泡
for (; i < len - 1; i++) {
int j = i;
for (; j < len - 1; j++) {
if (cmp((char*)arr + j*width, (char*)arr + (j + 1)*width) > 0) {
swap((char*)arr + j*width, (char*)arr + (j + 1)*width, width);
}
}
}
}
int main() {
int arr[] = { 1, 2, 6, 4, 2, 7, 4, 6, 3, 8, 9, 5 };
int i = 0;
bubble_sqort(arr, sizeof(arr) / sizeof(arr[0]), sizeof(int), int_cmp);
// 打印排序后的数组
for (; i < sizeof(arr) / sizeof(arr[0]); i++) {
printf("%d ", arr[i]);
}
printf("\n");
system("pause");
return 0;
}
运行结果: