I come, I see, I conquer

                    —Gaius Julius Caesar

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::


一、回调函数

 

    在计算机程序设计中,回调函数,是指通过函数参数传递到其它代码的,某一块可执行代码的引用。这一设计允许了底层代码调用在高层定义的子程序(如下图示)。 

 

   

 

 

二、 示例

 

#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;
}

 

图解:

 

 

【参考】

1、http://en.wikipedia.org/wiki/Callback_(computer_programming)

2、http://zh.wikipedia.org/wiki/回调函数

 

posted on 2012-04-28 16:55  jcsu  阅读(327)  评论(0)    收藏  举报