I do not want to use common blocks in my program. My main program calls a subroutine which calls a function. The function needs variables from the subroutine.
What are the ways to pass the set of information from the subroutine to the function?
program
...
call CONDAT(i,j)
end program
SUBROUTINE CONDAT(i,j)
common /contact/ iab11,iab22,xx2,yy2,zz2
common /ellip/ b1,c1,f1,g1,h1,d1,b2,c2,f2,g2,h2,p2,q2,r2,d2
call function f(x)
RETURN
END
function f(x)
common /contact/ iab11,iab22,xx2,yy2,zz2
common /ellip/ b1,c1,f1,g1,h1,d1,b2,c2,f2,g2,h2,p2,q2,r2,d2
end
So, basically you could solve this with something along these lines:
That is, just passing the parameters through. It is strongly encouraged to use modules, see Alexander McFarlane's answer, though it is not required. Alexander McFarlane shows how to pass f as an argument to the subroutine, such that you could use different functions in the subroutine, but your code does not seem to require this.
Now, this is an awful long list of parameters, and you probably do not want to carry those around all the time. The usual approach to deal with this, is to put those parameters into a derived datatype and then just passing this around. Like this:
This is just a rough sketch, but I got the impression this is what you are looking for.
What you care about here is association: you want to be able to associate entities in the function
f
with those in the subroutinecondat
. Storage association is one way to do this, which is what the common block is doing.There are other forms of association which can be useful. These are
Argument association is described in haraldkl's answer.
Use association comes through modules like
Host association is having access to entities accessible to the host. A host here could usefully be a module or a program
or even the subroutine itself
Below is an example of how you may achieve this...
The code has been adapted from a BFGS method to show how you can pass functions and call other functions within a module...
Here I use:
Hopefully this will cover everything for you...
func
anddfunc
would be declared within the program code that uses theMODULE Mod_Example
with an interface block at the top.res
,start
etc. can be declared with values in the main program block and passed toSUBROUTINE test_routine
as arguments.SUBROUTINE test_routine
will callprivate_func
with the variables that were passed to it.Your main program would then look something like this: