A variable's scope is the extent to which a field is visible to the program code. Variables have either global or local scope. A global variable is visible throughout the entire source member and is available to the entire set of mainline calcs and every subprocedure.
When a global variable is modified, the modified value is instantly visible throughout the entire source member because only one field of that name is in the source member. Unless a variable is declared inside a subprocedure, it is a global variable.
Global variables are good for program-wide values, constants, and of course, database input buffers (since we can't declare files in subprocedures, we have little choice in the matter).
Local variables are variables declared inside a subprocedure. They have limited scope: They exist only within the subprocedure in which they are declared. Once the subprocedure returns to its caller, the local variable is destroyed and its values lost.
A local variable can be retained between calls to its subprocedure. By adding the STATIC keyword to the variable's declaration, the variable's storage is moved to the global heap and is retained until the program ends. This gives the variable's storage a global lifecycle, but the variable is still visible only locally (i.e., within its subprocedure).
Name Collision
What happens if you declare a field in Subprocedure A and another field in Subprocedure B with the same name? Since fields declared in subprocedures are visible only to the code in the subprocedure itself, duplicating variable names in different subprocedures is not only permitted, it is a widespread practice.
There are no restrictions on this. The two fields of the same name in different subprocedures may have the same attributes, have completely different attributes, or share some common elements but differ in other ways. Each local variable is distinct to the subprocedure in which it is declared. That is, local variables behave as if they were declared in different programs.
What about declaring a local variable with the same name as a global variable? This practice is permitted, but unlike declaring a duplicate field name in multiple subprocedures, declaring a local variable with the same name as a global variable has consequences. First, in the mainline calcs, references to the variable name will access the global variable, while in the subprocedure, references to the variable name will access the local variable only. There is no way to access the global variable of the same name while in the subprocedure.
Local variables also include procedure interface fields (that is, the subprocedure parameters) as well as the %PARMS built-in function. When %PARMS is used within a subprocedure, it returns the number of parameters passed to the subprocedure. When %PARMS is used in the mainline calcs, it returns the number of parameters passed when the program was called.
LATEST COMMENTS
MC Press Online