Compilers Principles, Techniques, & Tools (purple dragon book) second edition exercise answers

Exercises for Section 2.8

2.8.1

For-statements in C and Java have the form:

for ( exprl ; expr2 ; expr3 ) stmt

The first expression is executed before the loop; it is typically used for initializing the loop index. The second expression is a test made before each iteration of the loop; the loop is exited if the expression becomes 0. The loop itself can be thought of as the statement {stmt expr3 ; }. The third expression is executed at the end of each iteration; it is typically used to increment the loop index. The meaning of the for-statement is similar to

expr1 ; while ( expr2 ) {stmt expr3 ; }

Define a class For for for-statements, similar to class If in Fig. 2.43.

Answer

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(){
    E1.gen();
    Label start = new Label();
    Label end = new Label();
    emit("ifFalse " + E2.rvalue().toString() + " goto " + end);
    S.gen();
    E3.gen();
    emit("goto " + start);
    emit(end + ":")
  }
}

2.8.2

The programming language C does not have a boolean type. Show how a C compiler might translate an if-statement into three-address code.

Answer

Replace

emit("ifFalse " + E.rvalue().toString() + " goto " + after);

with

emit("ifEqual " + E.rvalue().toString() + " 0 goto " + after);

or

emit("ifEqualZero " + E.rvalue().toString() + " goto " + after);