Starting from:
$35

$29

Assignment 5 Solution

    • Lexical/Dynamic Scoping

procedure main():

int var = 10;

procedure set_var(int val):

var = val;

end set_var

procedure proc1():

set_var(1);

end proc1

procedure proc2():

int var = 2;

set_var(4);

print var;

end proc2

print var;

set_var(41);

proc1();

print var;

proc2();

end main

    (a) Suppose the procedure main() uses static (lexical) scoping. What will it print, and why?

    (b) Suppose the procedure main() uses dynamic scoping. What will it print, and why?











1





    • Lexical Scoping

This problem uses the following procedure. This procedure uses static (lexi-cal) scoping.

procedure main():

int a;

procedure proc1(int i):

int b;

b = a + 1;

procedure recursion(int k):

print b;

b = b - 1;

if (b > 1):

recursion(k * b);

else:

a = k;

end recursion

b = b + i;

recursion(1);

end proc1

a = 1;

proc1(4);

print a;

end main

    (a) What does this procedure print? (Give the output of procedure main().)

    (b) Rewrite the procedure main() where each variable (argument vari-ables, declared variables, procedure names) is renamed by their (level, o set) pairs.

    (c) How does procedure proc1 nd variable a in instruction b = a + 1;? Show the RISC instructions corresponding to the high-level instruc-tion b = a + 1; in this procedure. You should use the same ILOC instruction format as used in class.

    (d) Show the stack frames at the beginning of procedure proc1. Label each frame with its procedures name, and make sure you include the


2





local variables and their values. Show all access links and control links between the stack frames, and the frame pointer (FP), by drawing arrows. You should use the frame layout in the gure below.



























Figure 1: Figure for the frame layout
























3

More products