C语言回调函数一个简单的例子

来源:互联网 发布:淘宝0点抢购秒杀怎么抢 编辑:程序博客网 时间:2024/06/13 07:42

回调函数通俗的解释:

     普通函数:你所写的函数调用系统函数,你只管调用,不管实现。

     回调函数:系统调用你所写的函数,你只管实现,不管调用。

以下是使用C语言实现回调函数的一个例子:

代码:

[cpp] view plain copy
  1. #include <stdio.h>  
      
    void PrintNum(int n);  
    void ShowNum(int n,void (* ptr)(int));  
      
    void PrintMessage1();  
    void PrintMessage2();  
    void PrintMessage3();  
    void ShowMessage(void (* ptr)());  
      
    int main(){  
       ShowNum(11111,PrintNum);  
       ShowNum(22222,PrintNum);  
       ShowMessage(PrintMessage1);  
       ShowMessage(PrintMessage2);  
       ShowMessage(PrintMessage3); 
       return 0;
    }  
      
    void PrintNum(int n){  
       printf("Test1 is called,the number is %d\n",n);  
    }  
      
    void ShowNum(int n,void (* ptr)(int)){  
       (* ptr)(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(void (* ptr)()){  
        (* ptr)();  
    }  

运行结果:

原创粉丝点击