怎么使用回调函数?
实例
#include<stdio.h>//头文件
int Callback_1() // Callback Function 1 无参函数1
{
printf("Hello, this is Callback_1 ");
return 0;
}
int Callback_2() // Callback Function 2 无参函数2
{
printf("Hello, this is Callback_2 ");
return 0;
}
int Callback_3() // Callback Function 3 无参函数3
{
printf("Hello, this is Callback_3 ");
return 0;
}
int Handle(int (*Callback)()) //定义一个函数指针,将函数的指针作为参数传入
{
printf("Entering Handle Function. ");
Callback(); //执行函数
printf("Leaving Handle Function. ");
}
int main()
{
printf("Entering Main Function. ");
Handle(Callback_1);//将函数的智者作为参数传入
Handle(Callback_2);
Handle(Callback_3);
printf("Leaving Main Function. ");
return 0;
怎么使用带参数的回调函数?
int Callback_1(int x) // Callback Function 1 //带参函数
{
printf("Hello, this is Callback_1: x = %d ", x);
return 0;
}
int Callback_2(int x) // Callback Function 2 //带参函数
{
printf("Hello, this is Callback_2: x = %d ", x);
return 0;
}
int Callback_3(int x) // Callback Function 3 //带参函数
{
printf("Hello, this is Callback_3: x = %d ", x);
return 0;
}
int Handle(int y, int (*Callback)(int)) //定义参数作为会掉函数的参数
{
printf("Entering Handle Function. ");
Callback(y); //执行
printf("Leaving Handle Function. ");
}
int main()
{
int a = 2;
int b = 4;
int c = 6;
printf("Entering Main Function. ");
Handle(a, Callback_1); //执行函数
Handle(b, Callback_2);
Handle(c, Callback_3);
printf("Leaving Main Function. ");
return 0;
}