ravi
ravi

Reputation:

Difficulty with fortran variable scope

I have intialized one variable in one of the fortran functions. I am using it in another function. But the value is not remains same. In other function call I am getting garbage value. How do i maintain the initialized value.

Ex:

entry a()
num_calls=0

entry b()
num_calls= num_calls + 1

From entry "b" i am getting num_calls as some garbage

Upvotes: 3

Views: 3126

Answers (4)

Kurt Glaesemann
Kurt Glaesemann

Reputation: 91

You should declare the variable with the "save" attribute. That way the variable lives between calls. There are compiler options to mark all variables as "save" since old compilers did this by default or depending upon optimization level.

    integer*4, save :: num_calls

It is a standard feature of most languages that local variables go undefined when they go out of scope.

Upvotes: 1

Tim Whitcomb
Tim Whitcomb

Reputation: 10677

For FORTRAN 77, Jonathan Leffler's method will work - as he points out, Fortran 90 and onward also supports COMMON blocks. However, since you have access to a Fortran 90/Fortran 2003 compiler, then there is no reason to use a COMMON block - leave them in the ash heap of history along with computed GOTO and ENTRY.

The Fortran 90 method for storing a group of related variables (and functions) is no longer the COMMON block but a MODULE. For your code, this is relatively straightforward:

module count_calls

    integer :: num_calls = 0

end module count_calls

Then, in your subroutines where you want to use num_calls, add

use count_calls

to either the subroutines themselves or the containing scope (i.e. a program or another module).

Upvotes: 4

Jonathan Leffler
Jonathan Leffler

Reputation: 754570

In classic Fortran (Fortran 77 or earlier), you'd ensure that num_calls is defined in a common block - probably a named common block.

COMMON /magic/ num_calls

I've not used Fortran 90, so I don't know what extra facilities it has. It likely retains named common blocks for backwards compatibility, but likely provides something better too.

I cheated, too, and used an implicit declaration of the variable. In full, I should write:

INTEGER*4 num_calls
COMMON /magic/ num_calls

Upvotes: 5

RBerteig
RBerteig

Reputation: 43356

You need to declare num_calls outside of either subroutine so that its lifetime is unrelated to either subroutine call. Someone who actually speaks FORTRAN can provide you some sample code...

Upvotes: 1

Related Questions