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.
1: program ScopeDemo; 2: var A : integer; 3: 4: procedure ScopeInner; 5: var A : integer; 6: begin 7: A := 10; 8: writeln (A) 9: end; 10: 11: begin (* Main *) 12: A := 20; 13: writeln (A); 14: ScopeInner; 15: writeln (A); 16: 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.
- Everybody can see global variables A, B, and C.
- However, in procedure Alpha the global definition of A is replaced by the local definition.
- Beta1 and Beta2 can see variables VCR, Betamax, and cassette.
- Beta1 cannot see variable FailureToo, and Beta2 cannot see Failure.
- No subprogram except Alpha can access F and G.
- Procedure Beta can call Alpha and Beta.
- Function Beta2 can call any subprogram, including itself (the main program is not a subprogram).