Homework 3:

Due Date: October 23


Points: 10

Assume the following program was compiled and executed using static scoping rules.   What value of x is printed in procedures sub1 ANSWER: X = 5 

REASON: Because the value of x is not declared in sub1, but it is declared in main, the static parent of sub1.  The computer goes first to sub1, wants to write x, but x is not instantiated here. So it goes to main, the static parent of sub1, (or, in other words, the next larger enclosing unit) finds the declaration for x, and prints the value declared therein, which is 5.  

Under dynamic scoping rules, what value of x is printed in procedure sub1 ANSWER: X = 10 

REASON:  Dynamic scoping is based on the calling sequence of subprograms, not on their spatial relationship to each other. GET IT?!

 Okay, let's try this...

Main establishes the value of x at 5. Then it calls sub2, which assigns x the value of 10, sub2 calls sub1, which prints x, whose value is now 10. Voila!

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}