回调函数简谈
回调函数就是一个通过函数指针调用的函数,如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外一个方调用的,用于对该事件或条件进行响应。
#include <stdio.h>
typedef int (*T)(int ,int); //这里定义了函数指针T
void Swp(int * x,int *y)
{
int z;
z = * x;
*x = *y;
*y = z;
}
void BubbleSort(int arr[],int size, T cmp) //传入的参数类型是函数指针T
{
for(int bound = 0;bound < size;bound++)
{
for(int cur = size - 1;cur > bound;cur--)
{
if(cmp(arr[cur -1],arr[cur]) == 0)
{
Swp(&arr[cur-1],&arr[cur]);
}
}
}
}
int less(int x,int y)
{
return x < y ? 1 : 0 ;
}
int main()
{
int arr[5] = {9,8,7,6,3};
BubbleSort(arr , 5 , less); //此处将函数less的地址作为参数传递
for(int i = 0; i < 5;i++)
{
printf("%d",arr[i]);
}
运行结果如下:
实际这是一个冒泡排序,采用了回调函数而已,相信这个例子大家容易理解。