Advanced Pascal Programming Language Problems

© 1998 by Dr. Thomas W. MacFarland -- All Rights Reserved


     Instructions:   Review the following program and see if you can 
                     predict the outcome by completing a "pencil 
                     trace" of the code.  

                     Program output is provided at the end of this 
                     page.

     Compiler:       The program was prepared using Standard Pascal 
                     on a UNIX-based host computer.


% cat PASCAL/advanced_pencil-02.p
{ Advanced Pascal Programming Language Exercises
  Dr. Thomas W. MacFarland
  advanced_pencil-02.p
}

{ The purpose of this program is to:

  1.  Demonstrate the use of global variables.

  2.  Demonstrate the use of local variables.

  3.  Demonstrate possible confusion when global variable names
      and local variable names are identical.
}

program Demonstrate_the_Scope_of_Global_and_Local_Variables;

var Sum   : integer;          {Global variable}
    Count : integer;          {Global variable}

procedure X;
var Sum: integer; {Notice how the variable Sum here is a local}
begin             {variable, but Count remains a global variable.}
   Sum := -1;
   writeln('Local Sum  =',Sum:5,'  Global Count = ',Count:5);
end; 

begin   (* Main program *)
   for Count := 0 to 3 do begin
      Sum := Count - 1;
      writeln('Global Sum =',Sum:5,'  Global Count = ',Count:5);
      X;
      writeln;
   end; 
end.  { advanced_pencil-02.p}
%  pc PASCAL/advanced_pencil-02.p
%  a.out
Global Sum =   -1  Global Count =     0
Local Sum  =   -1  Global Count =     0

Global Sum =    0  Global Count =     1
Local Sum  =   -1  Global Count =     1

Global Sum =    1  Global Count =     2
Local Sum  =   -1  Global Count =     2

Global Sum =    2  Global Count =     3
Local Sum  =   -1  Global Count =     3

Please send comments or suggestions to Dr. Thomas W. MacFarland

There have been [an error occurred while processing this directive] visitors to this page since February 1, 1999.