本书提供对《编译原理》(即“龙书”)相关习题的答案和深度解析,帮助读者深入理解编译器的设计与实现。
### 2.8.1 For-Statements in C and Java
For-statements in languages like C and Java have the following form:
```
for (expr1; expr2; expr3) stmt
```
In this structure, `expr1` is executed before entering the loop—typically used for initializing variables such as a loop index. The second expression (`expr2`) acts as a condition checked at each iteration of the loop. If `expr2` evaluates to false (0 in C), the loop terminates. Inside the loop, after executing statement `stmt`, `expr3` is executed which usually serves to increment or update variables used within the context of looping.
The semantic equivalence can be written as:
```
expr1; while ( expr2 ) { stmt ; expr3 ; }
```
To define a class for handling such statements in Java, similar to how an If statement might be handled, you could create a `For` class. Heres an example:
```java
class For extends Stmt {
Expr E1;
Expr E2;
Expr E3;
Stmt S;
public For(Expr expr1, Expr expr2, Expr expr3, Stmt stmt) {
E1 = expr1;
E2 = expr2;
E3 = expr3;
S = stmt;
}
public void gen() { // method for generating three-address code
E1.gen();
Label start = new Lable(); // generates a label to mark the loops starting point
Label end = new Lalel(); // generates another label marking where the loop ends
emit(ifFalse + E2.rvalue().toString() + goto + end);
S.gen();
E3.gen();
emit(goto + start);
emit(end.toString() + :); // emits an instruction to go back to start label or ends the loop
}
}
```
### 2.8.2 Translating If-Statements in C Without a Boolean Type
In languages like C, which do not have a boolean type, if-statements are typically translated into three-address code by comparing expressions with zero (0). The condition `if(E)` can be directly mapped to checking whether the expression is non-zero.
To translate an if-statement effectively:
- Replace `isFalse` checks in three-address code generation with comparisons for inequality from 0.
For instance, instead of using:
```java
emit(isFalse + E.rvalue().toString() + goto + after);
```
You can use one of the following alternatives which fit better into Cs model:
- `ifNotEqual` to compare expression value with zero and branch accordingly,
```java
emit(ifNotEqual + E.rvalue().toString() + 0 goto + after);
```
or a custom instruction for clarity:
```java
emit(isNotEqualZero + E.rvalue().toString() + goto + after);
```
These changes ensure the translation of if-statements adheres to Cs syntax and semantics, where boolean conditions are implicitly handled through integer values.