Reputation: 1324
I heard that, in Fortran77, all local variables in a function are created at the beginning of the main program execution and exist during the whole runtime, rather than being created on entry to the function and being destroyed on exit. I do not know whether this is still true in newer Fortran. Is there any way that can test this out? One test that meight help is to check whether variables retain their values between invocations. Here is a simple test:
program main
call p()
call p()
call p()
end program main
subroutine p()
real :: a(3)
a=a+1
write(*,*) a(1), a(2), a(3)
end subroutine p
My test using gfortran
indicates array a
retains its values between invocations, the same behavior as save
attribute being used.
I am wondering whether this is a standard in Fortran Language or depends on compiler implementations.
Upvotes: 2
Views: 402
Reputation: 7395
Just for fun, we can try a program where some other routine (e.g.foo()
) may be called between successive calls of p()
:
program main
call p()
! call foo() ! (*)
call p()
! call foo() ! (*)
call p()
end
subroutine p()
real :: a(3)
a = a + 1
write(*,*) "a = ", a
end
subroutine foo()
real :: b(3)
b = b * 10
write(*,*) "b = ", b
end
With the lines (*) commented, we get
! gfortran-8.2
a = 1.00000000 4.74066630E+21 1.00000000
a = 2.00000000 4.74066630E+21 2.00000000
a = 3.00000000 4.74066630E+21 3.00000000
! PGI18.10
a = 1.000000 1.000000 1.000000
a = 2.000000 2.000000 2.000000
a = 3.000000 3.000000 3.000000
while with the lines (*) uncommented, we get
! gfortran-8.2
a = 1.00000000 4.74066630E+21 1.00000000
b = 10.0000000 4.74066641E+22 10.0000000
a = 11.0000000 4.74066641E+22 11.0000000
b = 110.000000 4.74066623E+23 110.000000
a = 111.000000 4.74066623E+23 111.000000
! PGI18.10
a = 1.000000 1.000000 1.000000
b = 0.000000 0.000000 0.000000
a = 2.000000 2.000000 2.000000
b = 0.000000 0.000000 0.000000
a = 3.000000 3.000000 3.000000
(This is just an experiment/illustration of the behavior of local variables (i.e. not necessarily "SAVE-ed" as it might appear in a simpler case), and please see the other answer and comments for detailed explanations.)
Upvotes: 2
Reputation: 60008
Such a test cannot prove anything. The fact that some garbage remains in the stack between two function invocations can be a pure coincidence.
Local function variables are only valid during the function invocation in which their value was defined. That is also true in Fortran 77. If the value should be retained, the variables hhave to be declared SAVE
.
Upvotes: 2