next up previous contents
Next: Our Example Up: Simple Subroutines Previous: Introduction to Subroutine   Contents

Global Variables and Subroutines

A subroutine can ``see'' all global variables defined before its own definition. This can be used as a mechanism to pass information to a subroutine. For example, if we want to use a subroutine to print a number, we could write a program as follows:

var
  numToPrint: Integer;
  x, y : integer;

procedure printNum;
  begin
    writeln(numToPrint)
  end;

begin
  readln(x,y);
  numToPrint := x + y;
  printNum;
  numToPrint := x - y;
  printNum
end.

This program clumsily utilize subroutine printNum to print the sum and difference of x and y. Note how the value to be printed must be assigned to the global variable numToPrint first?

In the next chapter, we'll discuss better methods to pass information into and out of subroutines.



Tak Auyeung 2003-12-03