C语言回调函数

来源:互联网 发布:淘宝零食店货源哪里来 编辑:程序博客网 时间:2024/05/21 11:12

回调函数

回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。

例子

#include "stdafx.h"#include "stdio.h"  #include "stdarg.h"  #include "time.h" #include "log.h" #include <stdio.h>  static void printf_test(int i);  void (*fun_callback)(int i);int main(void)  {      //fun_callback = printf_test ;     if(fun_callback == NULL)    {        LOG("fun_callback NULL");    }    else    {        fun_callback(4);    }    sys_pause();}  static void printf_test(int a)  {      for(int i= 0;  i<=a;i++)    {            LOG("test i %d",i);     }} 

执行结果

这里写图片描述

例子

#include "stdafx.h"#include "stdio.h"  #include "stdarg.h"  #include "time.h" #include "log.h" #include <stdio.h>  static void printf_test(int i);  void (*fun_callback)(int i);int main(void)  {      fun_callback = printf_test ;     if(fun_callback == NULL)    {        LOG("fun_callback NULL");    }    else    {        fun_callback(4);    }    sys_pause();}  static void printf_test(int a)  {      for(int i= 0;  i<=a;i++)    {            LOG("test i %d",i);     }} 

执行结果

这里写图片描述

例子

#include "stdafx.h"#include "stdio.h"  #include "stdarg.h"  #include "time.h" #include "log.h" #include <stdio.h>  static void printf_test(int i);  void (*fun_callback)(int i);static void test_again(int i , void(*fun_callback_1)(int i));int main(void)  {      /*    fun_callback = printf_test ;     if(fun_callback == NULL)    {        LOG("fun_callback NULL");    }    else    {        fun_callback(4);    }    */    test_again(4,NULL);    test_again(4,printf_test);    sys_pause();}  static void printf_test(int a)  {      for(int i= 0;  i<=a;i++)    {            LOG("test i %d",i);     }} static void test_again(int i ,void(*fun_callback_1)(int i)){    if((*fun_callback_1) == NULL)    {        LOG("fun_callback NULL");    }    else    {        (*fun_callback_1)(4);    }}

执行结果

这里写图片描述

原创粉丝点击