Assignment 2: Scope and Lifetime

 

This assignment tests your understanding of scope and lifetime of variables. There are three questions, the first two of which are given in Pascal syntax, and the last involves the various kinds of variables in C.

 

  1. Consider the following program sketch in Pascal syntax. Assuming static scoping, add a procedure E local to procedure B such that it is unable to access the variable x, declared in B, but without altering the access to x of any other procedure. To do this you will have to change the program by adding one or more additional procedures (apart from E) in the appropriate place.

 

program P;

   procedure A;

   begin … end;

   procedure B;

     var x: integer;

     procedure C;

     begin … end;

     procedure D;

     begin … end;

   begin … end;

begin

…

end.

 

  1. Consider the following program sketch in Pascal syntax. Assuming dynamic scoping, give two calling sequences of procdures, starting with program P, and ending with a call to procedure C that result in C accessing the two different variables called x.

 

program P;

   procedure A;

   begin … end;

   procedure B;

      var x: integer;

      procedure C;

      begin … end;

      procedure D;

         procedure E;

         var x: integer;

         begin … end;

      begin … end;

   begin … end;

begin

…

end.

 

  1. In the following C program, how many times does the body of the loop run? Explain the effects of functions f and g on the value of  the variable y.

 

#include <stdio.h>

 

int y = 0;

 

void f() {

       int x = 0;

  x = x + 1;

  y = x;

}

 

void g() {

  static int x = 0;

  x = x + 2;

  y = x;

}

    

main() {

  int n = 0;

  while (y < 10) {

    n = n + 1;

    f();

    g();

  }

}

 

Grading

This assignment is worth 50 points. Questions 1 and 2 are worth 15 each, and the third is worth 20 points.

Submission

This assignment must be submitted through WebCT, so it must be prepared electronically. Read the drop box information page before submitting it. Pay close attention to the availability “window” of the assignment. When the window closes, you will not be able to submit an answer.