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

Exercises for Section 1.6

1.6.1

For the block-structured C code below, indicate the values assigned to w, x, y, and z.

int w, x, y, z;
int i = 4; int j = 5;
{
  int j = 7;
  i = 6;
  w = i + j;
}
x = i + j;
{
  int i = 8;
  y = i + j;
}
z = i + j;

Answer

w = 13, x = 11, y = 13, z = 11.

1.6.2

Repeat Exercise 1.6.1 for the code below.

int w, x, y, z;
int i = 3; int j = 4;
{
  int i = 5;
  w = i + j;
}
x = i + j;
{
  int j = 6;
  i = 7;
  y = i + j;
}
z = i + j;

Answer

w = 9, x = 7, y = 13, z = 11.

1.6.3

For the block-structured code of Fig. 1.14, assuming the usual static scoping of declarations, give the scope for each of the twelve declarations.

Answer

Block B1:
    declarations:  ->   scope
        w                B1-B3-B4
        x                B1-B2-B4
        y                B1-B5
        z                B1-B2-B5
Block B2:
    declarations:  ->   scope
        x                B2-B3
        z                B2
Block B3:
    declarations:  ->   scope
        w                B3
        x                B3
Block B4:
    declarations:  ->   scope
        w                B4
        x                B4
Block B5:
    declarations:  ->   scope
        y                B5
        z                B5

1.6.4

What is printed by the following C code?

#define a (x + 1)
int x = 2;
void b() { x = a; printf("%d\n", x); }
void c() { int x = 1; printf("%d\n", a); }
void main () { b(); c(); }

Answer

3

2