I have a program that calls a subroutine which then calls a function. I am somewhat confused by Fortran's requirements for function type declaration. I have declared the type in the function (i.e. real function foo(...)), and the program works whether or not I declare the function in the subroutine declaration section.
My specific question is, will not declaring the function in the subroutine potentially lead to unexpected behavior in future? I have also seen the interface block and am wondering if this is necessary as well.
More generally, I am also interested in what Fortran is doing "behind the scenes" and why it would be more or less important to declare the function or use an interface block.
EDIT: Some sample code:
program foo
real :: a,b,c
call bar(a,b,c)
end program foo
subroutine bar(a,b,c)
real :: a,b,c
c = baz(a,b)
end subroutine bar
real function baz(a,b)
real :: a,b
baz = a*b
end function baz
The best approach is to declare the function in the function, then to place the function in a module. Then "use" the function from any main program or procedure (subroutine or function) that calls that function. That way the calling program or procedure will be aware of the interface to the function and will generate the correct code. In Fortran terminology, the interface is explicit. If the function is called from a procedure in the same module, you don't have to "use" it because procedures in a module are aware of each other. See Computing the cross product of two vectors in Fortran 90 for an example. Typically there is no need to use an interface unless you are calling a procedure to which you lack the source code, or which is in another language, e.g., C accessed via the ISO C Binding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With