关于setjmp longjmp的使用

#include <stdio.h>
#include <setjmp.h>
#include <string.h>
#define DEBUG
jmp_buf jb_env;

#define CMD_ADD 1
#define CMD_SUB 2
#define CMD_MUL 3
#define CMD_DIV 4


#define GO_TO_START 0
#define ERR_DIV_ZERO  (11)
#define ERR_CMD (12)

double div(double lvar,double rvar);
void analysis_expr(char * str_exp);


#define LINE_MAX_SIZE 100
double lvar;
double rvar;
char   optr;
char str_exp[LINE_MAX_SIZE];

int
main()
{
    int setjmp_result = 0;
    switch((setjmp_result = setjmp(jb_env)))
    {
        case ERR_DIV_ZERO:
            printf("Divided by Zero!\n");
            break;
        case ERR_CMD:
            printf("Command error!\n");
            break;
    }

    printf("Enter<example:ADD 1 2>:");
    fgets(str_exp,LINE_MAX_SIZE,stdin);
    analysis_expr(str_exp);

    switch(optr)
    {
        case CMD_ADD:
            printf("%lf + %lf = %lf\n",lvar,rvar,lvar+rvar);
            break;
        case CMD_SUB:
            printf("%lf - %lf = %lf\n",lvar,rvar,lvar-rvar);
            break;
        case CMD_MUL:
            printf("%lf * %lf = %lf\n",lvar,rvar,lvar*rvar);
            break;
        case CMD_DIV:
            printf("%lf / %lf = %lf\n",lvar,rvar,div(lvar,rvar));
            break;
    }

    longjmp(jb_env,GO_TO_START);
}

void 
analysis_expr(char * str_exp)
{
    char * ptr = strtok(str_exp," ");    
    //解析符号;
    
    if(!strcasecmp(ptr,"add"))
        optr = CMD_ADD;
    else if(!strcasecmp(ptr,"sub"))
        optr = CMD_SUB;
    else if(!strcasecmp(ptr,"mul"))
        optr = CMD_MUL;
    else if(!strcasecmp(ptr,"div"))
        optr = CMD_DIV;    
    else{
        longjmp(jb_env,ERR_CMD);        
    }


    ptr = strtok(NULL," ");

    char * endptr = NULL;
    lvar = strtol(ptr,&endptr,10);
    if((*endptr)!=0)
    {
        longjmp(jb_env,ERR_CMD);
    }
    

    ptr = strtok(NULL," ");
    rvar = strtol(ptr,&endptr,10);
    if((*endptr!=0)&&(*endptr!='\n'))
    {
        printf("endptr:%d.",*endptr);
        longjmp(jb_env,ERR_CMD);
    }

    return ;    
}


double
div(double lvar,double rvar)
{
    if(rvar < 0.5 && rvar > -0.5)
        longjmp(jb_env,ERR_DIV_ZERO);

    return (lvar/rvar);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值