回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。
之前在
#include <stdio.h>
typedef int(*mypoint)(int);
static int fun1(int num)
{
printf("打印fun\n");
return num;
}
static int fun2(int num)
{
printf("不打印fun\n");
return num;
}
void test_fun(mypoint p)
{
p(11);
}
void test(int com)
{
//int(*pfun)(int);
mypoint pfun;
if (com > 1)
{
pfun = &fun1;
test_fun(fun1);
}
else
{
pfun = fun2;
}
test_fun(pfun);
}
int main()
{
test(-1);
//test_fun(fun1);
//test_fun(fun2);
return 0;
}
因为可以把调用者与被调用者分开,所以调用者不关心谁是被调用者。它只需知道存在一个具有特定原型和限制条件的被调用函数。简而言之,回调函数就是允许用户把需要调用的函数的指针作为参数传递给一个函数,以便该函数在处理相似事件的时候可以灵活的使用不同的方法