一、回调函数
在计算机程序设计中,回调函数,是指通过函数参数传递到其它代码的,某一块可执行代码的引用。这一设计允许了底层代码调用在高层定义的子程序(如下图示)。
二、 示例
#include <stdio.h>
#include <stdlib.h>
/* The calling function takes a single callback as a parameter. */
void PrintTwoNumbers(int (*numberSource)(void)) {
printf("%d and %d\n", numberSource(), numberSource());
}
/* A possible callback */
int overNineThousand(void) {
return (rand() % 1000) + 9001;
}
/* Another possible callback. */
int meaningOfLife(void) {
return 42;
}
/* Here we call PrintTwoNumbers() with three different callbacks. */
int main(void) {
PrintTwoNumbers(rand);
PrintTwoNumbers(overNineThousand);
PrintTwoNumbers(meaningOfLife);
return 0;
}
#include <stdlib.h>
/* The calling function takes a single callback as a parameter. */
void PrintTwoNumbers(int (*numberSource)(void)) {
printf("%d and %d\n", numberSource(), numberSource());
}
/* A possible callback */
int overNineThousand(void) {
return (rand() % 1000) + 9001;
}
/* Another possible callback. */
int meaningOfLife(void) {
return 42;
}
/* Here we call PrintTwoNumbers() with three different callbacks. */
int main(void) {
PrintTwoNumbers(rand);
PrintTwoNumbers(overNineThousand);
PrintTwoNumbers(meaningOfLife);
return 0;
}
图解:
【参考】
1、http://en.wikipedia.org/wiki/Callback_(computer_programming)
2、http://zh.wikipedia.org/wiki/åè°å½æ°

浙公网安备 33010602011771号