FCMP Procedure

Variable Scope in PROC FCMP Routines

The Concept of Variable Scope

A critical part of keeping routines and programs independent of one another is variable scope. A variable's scope is the section of code where a variable's value can be used. In the case of PROC FCMP routines, variables that are declared outside a routine are not accessible inside a routine. Variables that are declared inside a routine is not accessible outside the routine. Variables that are created within a routine are called local variables because their scope is “local” to the routine.
Functions use local variables as scratch variables during computations, and the variables are not available when the function returns. When a function is called, space for local variables is pushed on the call stack. When the function returns, the space used by local variables is removed from the call stack.

When Local Variables in Different Routines Have the Same Name

The concept of variable scope can be confusing when local variables in different routines have the same name. When this occurs, each local variable is distinct. In the following example, the DATA step and CALL routines subA and subB contain a local variable named x. Each x is distinct from the other x variables. When the program executes, the DATA step calls subA and subA calls subB. Each environment writes the value of x to the log. The log output shows how each x is distinct from the others.
proc fcmp outlib=sasuser.funcs.math;
   subroutine subA();
      call subB();
      put 'In subA: ' x=;

   subroutine subB();
      put 'In subB: ' x=;

options cmplib=sasuser.funcs;
data _null_;
   call subA();
   put 'In DATA step: ' x=;
SAS writes the following output to the log:
Output from Local Variables in Different Routines Having the Same Name
In subB:  x=subB
In subA:  x=5
In DATA step: x=99