Basic Pascal Tutorial/Chapter 4/Scope
English · Français · Български · 中文(中国) · 日本語
| ◄ | ▲ | ► |
|---|
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 a 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
20The reason is: if two variables 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 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.
- Everybody can see global variables
A, B, andC. - However, in procedure
Alphathe global definition ofAis replaced by the local definition. Beta1andBeta2can see variablesVCR, Betamax, andcassette.Beta1cannot see variableFailureToo, andBeta2cannot seeFailure.- No subprogram except
Alphacan accessFandG. - Procedure
Betacan callAlphaandBeta. - Function
Beta2can call any subprogram, including itself (the main program is not a subprogram).
| ◄ | ▲ | ► |
|---|
From the Free Pascal wiki, page "Basic Pascal Tutorial/Chapter 4/Scope", as the Internet Archive kept it on 2026-02-04, last changed on 2025-03-03. 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.
Talk about this page
Nobody has opened a bench for this page yet. Sign in to open one.

