Passing function names
as arguments
Integration
routines are general for a large class of functions. It makes sense to make the
routines independent of the specific function. Thus they are written for a
general function defined as fun in the following. Then in both C and Fortran
the function name fun1 is passed to the routine as the actual function to be
used. It is relatively important that the name fun should not be the name of an
actual function owing to the fact that some compilers can become confused by
this. #FortranArgs
C code
The C code is cpp\Mptrap.cpp
The line that passes a function in the
function header is given by.
double
amptrap(double a,double b,int n,double (*fun)(double));
The (*fun)(double)
notation is a pointer to a function. For this class just consider it as the
notation used to pass a function. Inside the routine amptrap the function call
uses this same notation except that (double) is replaced by the double
precision argument t.
for
(i=0;i<n;++i)
{t=(i+.5)*h+beg;
temp+=(*fun)(t);}
In the main code
which calls amptrap, the line is
anum=amptrap(beg,end,n1,fun1);
Where fun1 is the
name of the function being passed. I found details on doing this in USING C IN
SOFTWARE DESIGN by Ronald Leach. He also says incorrectly "Certainly
langauges such as Pascal, FORTRAN and BASIC have no such facility."
The
fortran code is for\Mptrap.for The function line for AMPTRAP is
FUNCTION
AMPTRAP(BEG,AEND,N,FUN)
The name FUN should
not refer to any actual function.
The working lines
in the FUNCTION AMPTRAP are.
DO I=1,N
T=(I-.5D0)*H+BEG
AMPTRAP=AMPTRAP+FUN(T)
ENDDO
It is not
dimensioned, so FORTAN assumes that it is a function.
The calling program
has the line
EXTERNAL FUN1
Preceding the
actual call. This line tells the compiler to look for a definition of FUN1
outside of this code.
ANUM2=AMPTRAP(BEG,AEND,N2,FUN1)