Procedure pointers
The pointer of the two previous lessons points at data; a procedure pointer points at code. The declaration names an interface instead of a type, procedure(iface), pointer :: f, and everything else works as it does for data: => associates, null() is the empty state, associated asks. This lesson chooses a function by name at run time, points at an intrinsic, and reads the error a function of the wrong shape gives.
A procedure pointer
The module below has two small functions with the same shape, a table of names, and pick, which returns the procedure pointer that matches a name. The shape is the abstract interface op_iface of lesson 6.12: one real in, one real out, and pure.
The file pp.f90:
module ops implicit none private public :: op_iface, pick, apply abstract interface pure function op_iface(x) result(y) real, intent(in) :: x real :: y end function op_iface end interface contains pure function twice(x) result(y) real, intent(in) :: x real :: y y = 2.0 * x end function twice pure function half(x) result(y) real, intent(in) :: x real :: y y = x / 2.0 end function half function pick(name) result(f) character(len=*), intent(in) :: name procedure(op_iface), pointer :: f select case (trim(name)) case ('twice') f => twice case ('half') f => half case ('exp') f => exp case default f => null() end select end function pick function apply(f, x) result(y) procedure(op_iface) :: f real, intent(in) :: x real :: y y = f(x) end function apply end module ops program ppdemo use ops implicit none procedure(op_iface), pointer :: f => null() character(len=8) :: names(3) integer :: i names = ['twice ', 'half ', 'exp '] do i = 1, 3 f => pick(names(i)) if (associated(f)) then print '(a,a,a,f8.3)', trim(names(i)), '(3.0) = ', ' ', apply(f, 3.0) else print '(a)', trim(names(i)) // ': no such operation' end if end do f => pick('nothing') print '(a,l1)', 'f associated after an unknown name = ', associated(f) end program ppdemo
gfortran -Wall -Wextra -std=f2018 pp.f90 -o pp
./pp
twice(3.0) = 6.000
half(3.0) = 1.500
exp(3.0) = 20.086
f associated after an unknown name = F
The loop calls three different functions through one name, and the fourth line is the state a table has to handle: a name nobody knows produces a null pointer, and the program says so instead of calling it.
Returning a pointer from a function
pick is a function whose result is a procedure pointer, declared in the function body: procedure(op_iface), pointer :: f. There is no result clause because the dummy name is the result, and the caller associates its own pointer with the result of the call. The target is a module procedure of the same module, so it lives as long as the program and the pointer is safe.
Returning a pointer to an internal procedure does not work: the procedure does not outlive its host, and a pointer to it is dangling the moment the host returns. That is the same lifetime rule as for data, and it is the reason a factory of operations lives in a module.
An intrinsic as a target
f => exp points at the intrinsic function, because the intrinsic has the shape the interface describes. An intrinsic is not passed by name and does not need an external statement; the compiler checks the arguments and the result against the interface at the assignment, which is more than C gives a function pointer and less than a template gives.
A pointer to an intrinsic is useful for building a numerical interface in which the function is a parameter, for example a table of activation functions or a table of kernels. It also shows the limit: the pointer fixes the precision, so an interface of real(real64) cannot point at the single-precision exp, and the error is the next section.
The null procedure pointer
=> null() works for a procedure pointer exactly as for a data pointer, and associated answers the same question. What is different is the consequence of getting it wrong: calling a null procedure pointer is a jump to address zero, and no compiler option in this image turns it into a message. Test before the call, as the loop above does.
A pointer dummy for a procedure argument may also be optional, and then present(f) answers whether the caller passed one at all. The two questions are different: a caller may pass a pointer that is null, and a caller may pass nothing.
An intrinsic with the wrong shape
The interface is compared with the target at the pointer assignment, and a function of two arguments does not fit a shape with one:
program badintrinsic implicit none abstract interface pure function op_iface(x) result(y) real, intent(in) :: x real :: y end function op_iface end interface procedure(op_iface), pointer :: f => null() f => atan2 print *, f(1.0) end program badintrinsic
gfortran -Wall -Wextra -std=f2018 badintrinsic.f90 -o badintrinsic
badintrinsic.f90:13:7:
13 | f => atan2
| 1
Error: Interface mismatch in procedure pointer assignment at (1): 'atan2' has the wrong number of arguments
The message names the count rather than the types, because that is the first thing the compiler compared. Swap in a function with one argument and the wrong result and the message becomes "Type mismatch in function result", as in lesson 6.12.
When a procedure pointer pays
It pays where a program has to choose an operation while it runs: a solver that reads its method from the command line, a library that lets the caller register a callback, a table of kernels chosen by the hardware. In all three the choice is data rather than control flow, and a pointer is what stores it.
It costs an indirect call and it costs a reader who has to find where the pointer was set. When the choice is fixed at compile time, a dummy procedure argument (lesson 6.12) or a select case that calls plain functions is easier to follow, and the compiler can inline both. A profile that shows the call in the hot loop is the argument for a pointer; taste is the argument against.
Exercises
- Add squ to the module and a name 'square' to pick. Which lines change?
- Call apply(f, 3.0) before the first f => pick(...) with f left at null(). What happens, and why is it not a compile error?
- Point f at sin and print apply(f, 0.0). What is the value?
- Make the dummy of apply optional and test with present(f) before the call. Which two states can the caller be in?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
procedure(op_iface), pointer :: fdeclare?Answer
A pointer whose target is a procedure with the shape of op_iface
The interface gives the shape; the pointer gives the storage.
-
What does
f => expdo?Answer
Points the pointer at the intrinsic EXP
An intrinsic with the right shape is a valid target.
-
What does this program print?
program p implicit none abstract interface pure function f1(x) result(y) real, intent(in) :: x real :: y end function f1 end interface procedure(f1), pointer :: g => null() g => abs print *, g(-2.5) print *, associated(g) end program pAnswer
2.50000000 and T
ABS matches the shape and the pointer is associated.
-
What happens when a null procedure pointer is called?
Answer
The program jumps to an invalid address and crashes
There is no check; test with ASSOCIATED first.
-
Why does
present(f)andassociated(f)ask different questions?Answer
A caller may pass a null pointer, or pass no argument at all
Absence and nullness are two separate states.
-
What does gfortran report for
f => atan2with a one-argument interface?Answer
Interface mismatch in procedure pointer assignment: wrong number of arguments
The shape is compared where the pointer is assigned.
-
Why can a procedure pointer not point at an internal procedure safely?
Answer
The internal procedure does not outlive its host
The pointer would dangle when the host returns.
-
What does a pointer to an intrinsic fix?
Answer
The interface, including the precision of the arguments
A real64 interface cannot point at the single-precision EXP.
-
What is the cost of a procedure pointer call?
Answer
An indirect call that cannot be inlined
The target is only known when the call runs.
-
When is a dummy procedure argument better than a procedure pointer?
Answer
When the choice is fixed at the call site and never changes
A dummy argument is simpler and easier for the compiler.
The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev