---
title: "虎书P8问题(1)"
author: "pf_miles"
date: "2008-08-16T20:04:07Z"
tags: ["C", "C#", "C++"]
slug: "p8-1"
draft: false
lastmod: "2008-08-16T20:04:07Z"
id: 228759
url: "https://pf-miles.iteye.com/blog/228759"
---

见《虎书》中文版第８页；
我的答案：


```c

#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

```



```c

#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:

```c

#include <stdio.h>
#include "util.h"
#include "prog1.h"
#include "slp.h"
#include "p8q1.h"

main(){
    printf("%d\n",resolveStm(prog()));
}


```

输出结果：2

体会：对于“目标”需要特殊处理，“目标”就是解析程序的出口。