Contents Up << >>

Scope rules

Certain constructs in the language (entities, subprograms, blocks, etc.) have what is called a scope. When an object is declared in these constructs, they are declared in the scope associated with that construct and cannot normally be referenced outside of that scope. If one of these constructs is declared within another of these objects, then the scope of the former is said to be at a lower level then the latter. In a given construct, any object declared within the scope of that construct can be referenced, as well as any object declared in a scope of a higher level. This may sound difficult to understand, but it is easy to see with an example.

The following declarations declare three subprograms. Since the the procedures b and c are contained within the procedure a, the body of procedures b and c can refer to objects declared in procedure a as well as their own declarations. The fact that procedures b and c are on a next lower level than procedure a is visually indicated by indenting the procedures b and c. This is a good programming style and makes programs more readable. Notice that procedure b and c are on the same level since they are both declared within procedure a. Procedure b can reference its own variables, as well as the variables of procedure a, but not variable j of procedure c because it is not in procedure b's scope or in a scope of a higher level. Likewise, procedure c can not refer to variable i of procedure b. There are two variables named x that are visible to (can be referenced by) procedure b. If x is referenced in procedure b, then it will refer to the variable of the lowest level, in this case the x declared in procedure b.