链式函数

#include <stdio.h>

typedef struct{
    int v;
    int (*next)(void);
    int (*error)(void);
} context_t;

context_t *ctx;

int start_step();
int a_step();
int b_step();
int c_step();
int finish_step();
int error_step();

int a_step()
{
    printf("a step  ctx = %c\n",ctx->v);
    int (*run_next)(void)= ctx->next;
    ctx->v = 'a';
    ctx->next = c_step;
    return run_next();
}

int b_step()
{
    printf("b step  ctx = %c\n",ctx->v);
    if(0){
        return ctx->error();
    }
    
    int (*run_next)(void)= ctx->next;
    ctx->v = 'b';
    ctx->next = finish_step;
    return run_next();
}

int c_step()
{
    printf("c step  ctx = %c\n",ctx->v);
    int (*run_next)(void)= ctx->next;
    ctx->v = 'c';
    return run_next();
}


int error_step()
{
    printf("error ctx = %c\n",ctx->v);
    ctx->v = 'e';
    return -1;
}



int start(int data)
{
    printf("start\n");
    context_t d;
    ctx  = &d;
    d.v = data;
    ctx->next = b_step;
    ctx->error = error_step;
    a_step();
    printf("final v = %c \n",ctx->v);
    
    return 0;
}
int finish_step()
{
    printf("finish ctx = %c \n",ctx->v);
    ctx->v = 'f';
    return 0;
}

int main()
{
    start('s');        
    return 0;
}

 

转载于:https://www.cnblogs.com/ruanjianxian/p/10056711.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值