虎书P8问题(1)

见《虎书》中文版第8页;
我的答案:


#ifndef P8Q1_H
#define P8Q1_H
#include "slp.h"

int resolveStm(A_stm stm);
int resolveExp(A_exp exp);
int resolveExpList(A_expList expList);
int countExpInExpList(A_expList expList);

#endif



#include "p8q1.h"

int resolveStm(A_stm stm){
int temp1 = 0, temp2 = 0;
if(stm->kind == A_compoundStm){
temp1 = resolveStm(stm->u.compound.stm1);
temp2 = resolveStm(stm->u.compound.stm2);
return temp1>temp2? temp1:temp2;
}else if(stm->kind == A_assignStm){
return resolveExp(stm->u.assign.exp);
}else if(stm->kind == A_printStm){// the way out
return countExpInExpList(stm->u.print.exps);
}else{
return 0;
}
}

int countExpInExpList(A_expList expList){
if(expList->kind == A_lastExpList){
return 1;
}else if(expList->kind == A_pairExpList){
return 1 + countExpInExpList(expList->u.pair.tail);
}else{
return 0;
}
}

int resolveExpList(A_expList expList){
int temp1,temp2;
if(expList->kind == A_pairExpList){
temp1 = resolveExp(expList->u.pair.head);
temp2 = resolveExpList(expList->u.pair.tail);
return temp1>temp2?temp1:temp2;
}else if(expList->kind == A_lastExpList){
return resolveExp(expList->u.last);
}else{
return 0;
}
}

int resolveExp(A_exp exp){
int temp1,temp2;
if(exp->kind == A_idExp){
return 0;
}else if(exp->kind == A_numExp){
return 0;
}else if(exp->kind == A_opExp){
temp1 = resolveExp(exp->u.op.left);
temp2 = resolveExp(exp->u.op.right);
return temp1>temp2?temp1:temp2;
}else if(exp->kind == A_eseqExp){
temp1 = resolveStm(exp->u.eseq.stm);
temp2 = resolveExp(exp->u.eseq.exp);
return temp1>temp2?temp1:temp2;
}else{
return 0;
}
}



main.c:

#include <stdio.h>
#include "util.h"
#include "prog1.h"
#include "slp.h"
#include "p8q1.h"

main(){
printf("%d\n",resolveStm(prog()));
}


输出结果:2

体会:对于“目标”需要特殊处理,“目标”就是解析程序的出口。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值