您的位置:首页 > 编程语言 > C语言/C++

C语言的回调函数

2016-07-13 19:57 330 查看
> 回调函数与普通函数的对比


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

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

简单来说就是函数A里面有函数指针,指向你需要调用的函数B,这样子函数B就能够随便写,程序的通用性也增强了。

#include <stdio.h>

void PrintNum(int n);
void ShowNum(int n,void (* ptr)());

void PrintMessage1();
void PrintMessage2();
void PrintMessage3();
void ShowMessage(void (* ptr)());

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,void (* ptr)()){
(* 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)();
}


程序运行结果



参考链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 函数 指针