[banner image]
taoyue.com : Learn Pascal tutorial : 4D - Scope

Scope refers to where certain variables are visible. You have procedures inside procedures, variables inside procedures, and your job is to try to figure out when each variable can be seen by the procedure.

A global variable is a variable defined in the main program. Any subprogram can see it, use it, and modify it. All subprograms can call themselves, and can call all other subprograms defined before it.

The main point here is: within any block of code (procedure, function, whatever), the only identifiers that are visible are those defined before that block and either in or outside of that block.

program ScopeDemo;
var A : integer;

  procedure ScopeInner;
  var A : integer;
  begin
    A := 10;
    writeln (A)
  end;

begin (* Main *)
  A := 20;
  writeln (A);
  ScopeInner;
  writeln (A);
end. (* Main *)

The output of the above program is:

20
10
20

The reason is: if two variable with the same identifiers are declared in a subprogram and the main program, the main program sees its own, and the subprogram sees its own (not the main's). The most local definition is used when one identifier is defined twice in different places.

Here's a scope chart which basically amounts to an indented copy of a program with just the variables and minus the logic. By stripping away the application logic and enclosing blocks in boxes, it is sometimes easier to see where certain variables are available.

[Image of scope chart]

<<< Previous Table of Contents Next >>>