回调函数是函数指针的一种应用:
简而言之,回调函数是一个通过函数指针调用的函数。如果你把函数指针(函数的入口地址)传递给另一个函数,当这个函数指针被用来调用它所指向的函数时,我们就说这个函数是回调函数。
例:
int add(int x, int y) //回调函数
{
return x+y;
}
int sub(int x, int y) //回调函数
{
return x-y;
}
int call(int(*p)(int,int), int x, int y) //p为函数指针 传入参数必须符合p指针指向函数的类型
{
return p(x,y); //通过函数指针调用函数
}
int main(int argc, char *argv[])
{
int a = 5, b = 3,c;
c =call(add,a,b); //传入add的地址
printf("%d ",c);
c=call(sub,a,b); //传入sub的地址
printf("%d ",c);
}