回调函数的范例———VS2010 下编译

1.回调函数范例一,在VS2010下编译通过

#include "stdafx.h"
#include <stdio.h>

void printWelcome(int len)
{
       printf("欢迎欢迎 -- %d\n", len);
}
 
void printGoodbye(int len)
{
       printf("送客送客 -- %d\n", len);
}
 
void callback(int times, void (* print)(int))
{
       int i;
       for (i = 0; i < times; ++i)
       {
              print(i);
       }
       printf("\n我不知道你是迎客还是送客!\n\n");
}
void main(void)
{
       callback(10, printWelcome);
       callback(10, printGoodbye);
       printWelcome(5);
}
运行结果如下


2.回调函数的范例二,在VS2010 下编译,通过

#include <stdio.h>
#include   <conio.h>  
#include   <stdlib.h>
#include "stdafx.h"

int my_strcmp(char* des, char* src);
static void cmd_hello(void);
static void cmd_hi(void);
static void cmd_exit(void);


//定义一个函数指针
 typedef void (*callback)(void);
 //定义命令结构体
 typedef struct cmd{
     char name[10];  //命令的名字
     callback func;  //与命令相对应的函数指针
 }cmd_t;

//然后定义一个命令数组:
 
 //声明命令数组
 cmd_t cmd_tbl[] = {
     {"hello",cmd_hello},
     {"hi",cmd_hi},
     {"exit",cmd_exit},
 }; 
//  跟命令相对应的函数为:
 
 //相对应的功能函数为:
 
 void hello(void)
  {
     printf("hello\n");
  }
 void hi(void)
  {
     printf("hi\n");
 }

  static void cmd_hello(void)
  {
      hello();
  }
  
  static void cmd_hi(void)
  {
      hi();
  }
  
  static void cmd_exit(void)
  {
    //exit(0);
  } 


 
//此时我们还需要一个查找命令函数:
 
 cmd_t* my_find( char* val)
 {   
	 int i;
     for(i = 0; i < sizeof(cmd_tbl)/sizeof(cmd_tbl[0]); i++){
         if(!my_strcmp(val,cmd_tbl[i].name)){
             return &cmd_tbl[i];
         }
     }
     return 0;
 } 

 //字符串比较函数
int my_strcmp(char* des, char* src)
{
    while(*des){
        if(*des != *src)
            return 1;
        des++;
        src++;
    }
    return *src - *des;
}

//此函数返回的是一个结构体指针,若没有找到命令则返回0;
 
//main 函数如下:
 
  int main(void){
      char val[20] = {};
      cmd_t *cmd_ptr;
      while(1){
          gets(val);
          cmd_ptr = my_find(val);
         if(cmd_ptr){
             cmd_ptr->func();
         }
         else{
             printf("no cmd\n");
         }
     }
     return 0;
 }
运行结果:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值