Homework #3

Group Members:

Mei Fun Wong, Meng Yi Yee and Carrie Neer

 

  1. Assume the following program was compiled and executed using static scoping rules.   What value of x is printed in procedures sub1?   Under dynamic scoping rules, what value of x is printed in procedure sub1?

program main;

var x : integer;

procedure sub1;

begin {sub1}

writeln('x = ', x)

end; {sub1}

procedure sub2;

var x : integer;

begin {sub2}

x := 10;

sub1;

end; {sub2}

begin {main}

x := 5;

sub2;

end. {main}

 

Answer:

Static Scooping: In static scooping, the form of variable is looked up in the nearest block (surcase). If the variable is not found than the variable in the nearest/smallest containing block is taken. In this case, the value for x in sub1 is 5.

 

 

Dynamic Scooping: In dynamic scooping, the form of variable is looked up in the current block. If the varible is not found then the calling block is looked up until the variable is found. In this case, the value printed for x in sub1 is 10.

 

Reference: