passing a function as an argument

142 views
Skip to first unread message

Ken

unread,
Feb 1, 2012, 6:36:24 PM2/1/12
to gg95
I've seen sample code where a function name is passed as a argument to
a function or subroutine and then declared as an external function.
What is actually being passed? An address?

Ken

Damian Rouson

unread,
Feb 6, 2012, 11:30:59 AM2/6/12
to gg...@googlegroups.com
In case you haven't received a response, I suggest posting your question to the comp.lang.fortran newsgroup.  (Note: if you search the web for the newsgroup, you'll undoubtedly find the Google interface to it, which is overrun with spam.  Not to worry: it is actively read by Fortran language experts who will respond, but you might do best to read the responses through a newsreader.  I use the open-source SeaMonkey software.)

I don't know the details of what gets passed when you pass a function name.  I do believe it's more flexible to use the Fortran 2003 procedure pointer construct instead.  I believe the latest version of most compilers support this feature (without checking, I'd bet IBM, Cray, Portland Group, gfortran, and Intel all support procedure pointers).

Damian



Ken

--
You received this message because you are subscribed to the Google Groups "gg95" group.
To post to this group, send email to gg...@googlegroups.com.
To unsubscribe from this group, send email to gg95+uns...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/gg95?hl=en.


Tobias Burnus

unread,
Feb 7, 2012, 1:30:49 PM2/7/12
to gg95
Yes, one passes the address of the procedure. By contrast, with
procedure pointers, you pass the address of the pointer variable,
which contains the address of the procedure. Example usage:

module m
subroutine p()
print *, 'Hello'
end subroutine p
subroutine foo (f, g)
procedure() :: f
procedure(), pointer :: g
call f()
call g()
end subroutine foo
end module m

program test
use m
procedure(), pointer :: proc_ptr
proc_ptr => p
call foo (p, proc_ptr)
end program test

Here, "p" is the passed procedure, "proc_ptr" is a pointer variable,
which contains the address of "p".

Note that Equivalent to using
procedure() :: f
the following:
external f

A better choise is to use:
procedure(p) :: f
procedure(p), pointer :: g
Then the interface is known to the compiler. The first line is
equivalent to
interface
subroutine f()
end subroutine f
end interface

The other line is equivalent to the following, but I think not all
compilers support it:
interface
subroutine g()
end subroutine g
end interface
pointer :: g

The procedure statement - and procedure pointers - are Fortran 2003
features. By now, most compilers have implemented it. I know that
gfortran supports it (full support since 4.5). Also g95 supports it
since years, though it does not seem to support the last version.

Tobias
Reply all
Reply to author
Forward
0 new messages