next up previous contents
Next: Global Storage Up: The Building Blocks of Previous: Scope of Variables   Contents

Lifetime of Variables

A variable is "alive" when its name is associated with a memory location. A variable is "alive" during the execution of the program unit that declared it:

SAVE attribute makes the variable static. It is allocated in a static part of the memory and is never deallocated (during the execution of our program). In particular static variables preserve their value between calls. Here is an example of a subroutine which counts how many times it has been called. The variable icount is static due to the initialization.

 
subroutine icount(iarg)
implicit none
  integer :: iarg     ! an argument
  integer :: ilocal=0 !local variable, static storage
  ilocal=ilocal+1
  print*,'I have been called ',ilocal,' time(s).'
end subroutine icount

Instead of initializing it, one can make the variable ilocal static using

 
integer, save :: ilocal
save ilocal
A single SAVE statement not followed by a list of variables has the effect of declaring static (``saving'') all local entities in a program unit that can be saved (note that formal (dummy) arguments and automatic arrays cannot be saved).


next up previous contents
Next: Global Storage Up: The Building Blocks of Previous: Scope of Variables   Contents
Adrian Sandu 2001-08-26