Scope of variables in Fortran

Categories: Code

Fortran has an option of local variables called SAVE. If this option is added, its value will be kept until the end of program. To clarify, let's say if the code is like the following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
program main
  integer :: a = 1
  write(*,*) "a=",a
  call add1(a)
  write(*,*) "a=",a
  call add1(a)
  write(*,*) "a=",a
end program

subroutine add1(a)
  integer,save :: b
  integer :: a
  write(*,*) "b=",b
  b=1
  a = a+b
  b = b+1
end subroutine

No matter how do you compile it, the output will be like the following:

1
2
3
4
5
 a=           1
 b=           0
 a=           2
 b=           2
 a=           3

See, the value of b=2 is saved when the subroutine is called for the first time.

Now, if we remove the SAVE flag and compiled with gfortran and ifort:

1
2
gfortran -o test test.f90
ifort -o testI test.f90

Gfortran gives the following results, clearly it assumes the variable is not saved

1
2
3
4
5
 a=           1
 b=       32740
 a=           2
 b=       32740
 a=           3

Ifort gives the following, also not saved:

1
2
3
4
5
 a=           1
 b=           0
 a=           2
 b=           0
 a=           3

Interestingly, it can be also found the initial value given to b is different.

To save the value of b, some flags are needed.

ifort gfortran location of variable
save -noauto/-save -fno-automatic (might be heap? IDK)
no-save -auto(default)/-nosave(legacy)/-automatic(legacy) -fautomatic(default) stack

However, it should be noted that -noauto and -fno-automatic will be conflicted with -recursive/-frecursive/-fopenmp/-openmp

In addition, for gfortran it's better to set -finit-local-zero and set -zero for ifort.

comments powered by Disqus