tags:

views:

175

answers:

4

Hi, 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

+1  A: 

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...

RBerteig
+4  A: 

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
Jonathan Leffler
A: 

its working in f90 without initialize.. but why its not working with fortran 2003 compiler?

You will find that an answer isn't a good place to carry on a conversation on SO. That is what the `add comment` link below every question and answer is for. Or, you can edit your question to refine it. The new question here should be edited into the question, for example.
RBerteig
+1  A: 

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).

Tim Whitcomb