Assignment 2
- Consider the following code written in a language with nested subroutines:
procedure main()
a : integer
procedure B(a : integer)
x : integer
procedure A(n : integer)
a := n
procedure R(m : integer)
write_integer(x)
x = x – 2
if x > 1
R(m + 1)
else
A(m)
–– body of B
x := a × a
R(1)
–– body of main
B(2)
write_integer(a)
- What does this program print assuming static scope, respectively dynamic scope? Explain your answer.
- Show the frames on the stack when procedure A has just been called. For each frame, show the values of the local variables and the static links.
- Consider the following pseudocode with nested subroutines:
- procedure main()
- a : integer := 1
- b : integer := 2
- c : integer := 3
- procedure first()
- a : integer := c
- c : integer := b
- procedure second()
- c : integer := 4
- –-body of second
- print a, b, c
- b : integer := 5
- –body of first
- second()
- print a, b, c
- –body of main
- first()
- print a, b, c
What does the program print (or will the compiler identify static semantic errors) if we assume that:
- names must be declared before use, and the scope of a name extends from its declaration through the end of the block?
- names must be declared before use, but the scope of a name is the entire block in which it is declared?
- Consider the following program written in generic pseudocode:
int x = 1;
int a[3] = { 2, 5, 3 };
void foo(int u, int v) {
v = a[x];
v = u * 9;
x = 2;
a[2] = u;
u = u – 2;
print u;
print v;
print x;
}
int main() {
foo(a[x], a[2]);
print x;
print a[0];
print a[1];
print a[2];
}
What is the output printed when this program is executed using call by value-result, respectively, call by macro expansion? Explain what happens in each case.