HP Fortran Programmer's Guide (B3908-90031; September 2011)

Controlling data storage
Automatic and static variables
Chapter 3 105
CALL recurse
CONTAINS
! This subroutine calls itself four times.
! Each time it is called, it adds 1 to the values in
! stat_val and auto_val and displays the result.
! stat_val has the SAVE attribute and therefore is
! pre-initialized and retains its value between calls.
! auto_val is an automatic variable and therefore has
! an unpredictable value (plus 1) at each call.
RECURSIVE SUBROUTINE recurse
INTEGER(KIND=1), SAVE :: stat_val
INTEGER(KIND=1) :: auto_val
stat_val = stat_val + 1
auto_val = auto_val + 1
PRINT *, ‘stat_val = ‘, stat_val
PRINT *, ‘auto_val = ‘, auto_val
IF (stat_val < 4) THEN
CALL recurse()
END IF
END SUBROUTINE recurse
END PROGRAM main
Following are the command lines to compile and execute this program, along with sample output. Notice
that stat_val regularly increments at each call. The reason is that it is a static variable and therefore
retains its value between calls. But auto_val is not actually incremented; it is an automatic variable and is
given a fresh (and uninitialized) memory location at each call. In other words, the subroutine adds 1 to
whatever value happened to be in the memory location that was allocated to auto_val at the start of the
call:
$ f90 recursive.f90
$ a.out
stat_val = 1
auto_val = 124
stat_val = 2
auto_val = 1
stat_val = 3
auto_val = 65
stat_val = 4
auto_val = 65