Algorithm by C/C++ : Callback function

来源:互联网 发布:淘宝美瞳店铺哪个好 编辑:程序博客网 时间:2024/06/05 03:29


1. general description

Developers are often confused  by what  a callback function is because of the name of the thing.
A callback function is a function which is:
①. passed as an argument to another function
②. invoked after some kind of event.
Once its parent function completes, the function passed as an argument is then called.



The so-called callback, is the module A through a function B() to complete a certain function, but the function a() is the callback function.

The definition of the callback function pointer is defined in module B, and the registration function is also implemented.


2. Demo and Codes

#include <stdio.h>  typedef void (*CallBackFun)(int p); typedef void (*CallBackMessage)(void); void PrintNum(int n);  void ShowNum(int n,CallBackFun x);   void ShowMessage(CallBackMessage x);void PrintMessage1();  void PrintMessage2();  void PrintMessage3();    int main(){     ShowNum(11111,PrintNum);     ShowNum(22222,PrintNum);     ShowMessage(PrintMessage1);     ShowMessage(PrintMessage2);     ShowMessage(PrintMessage3);  }    void PrintNum(int n){     printf("Test1 is called,the number is %d\n",n);  }    void ShowNum(int n,CallBackFun x){     x(n);}     void PrintMessage1(){     printf("This is the message 1!\n");  }    void PrintMessage2(){     printf("This is the message 2!\n");  }    void PrintMessage3(){     printf("This is the message 3!\n");  }  void ShowMessage(CallBackMessage x){      x();}  

Author:Kyrie




0 0
原创粉丝点击