HP Fortran Programmer's Guide (September 2007)
Controlling data storage
Automatic and static variables
Chapter 3100
Automatic and static variables
By default, HP Fortran allocates stack storage for program variables. Such variables are
called automatic variables because they are allocated at each invocation of the program
unit in which they are declared.
Static variables are allocated storage from static memory when the program is first loaded
into memory. They remain allocated for the life of the program.
HP Fortran allocates static storage for the following variables:
• Variables specified in a COMMON or EQUIVALENCE statement.
• Variables initialized in a type declaration statement or in a DATA statement.
• Variables specified in a SAVE or STATIC statement. A SAVE statement without a variable
list specifies static storage for all variables in the scoping unit.
• Variables in program files that have been compiled with the +save or +Oinitcheck
command-line option. See “Uninitialized variables” on page 238 for information about
using these options when porting.
Static variables have two characteristics that are of special interest:
• They are set to 0 or null value at load-time.
• They do not require re-initialization at each invocation of their program unit.
Static variables have several disadvantages. In Fortran programs that use recursion, static
variables can defeat one purpose of recursion—to provide a fresh set of local variables at each
recursive call. Also, the widespread use of static variables in a program can slow its
performance: static variables are ineligible for such fundamental optimizations as register
allocation, and they can limit the optimization of program units that use them.
The following example program illustrates the difference between automatic and static
variables. The program consists of a main program unit that calls a recursive internal
subroutine. The subroutine increments two variables (stat_val and auto_val), prints the
updated variables, and then calls itself recursively. Neither of the two variables is explicitly
initialized, but stat_val is declared with the SAVE attribute, which means that it is allocated
static storage and is pre-initialized to 0 by the compiler.
The program is shown below.