Sign in Join
Wiki copytemporary

Revision 1 of 2, by Kai Burghardt on 8-20-2022. The page as it is now.

Basic Pascal Tutorial/Chapter 4/Scope

4D - Scope (author: Tao Yue, state: unchanged)

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.

pascal
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. centre


From the Free Pascal wiki, page "Basic Pascal Tutorial/Chapter 4/Scope", as it stood on 2022-08-20 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.