Fortran Procedures - Functions and Subroutines Referencing a procedure


For a function or subroutine to be useful it has to be referenced. A subroutine is referenced in a call statement

call sub(...)

and a function within an expression. Unlike in many other languages, an expression does not form a complete statement, so a function reference is often seen in an assignment statement or used in some other way:

x = func(...)
y = 1 + 2*func(...)

There are three ways to designate a procedure being referenced:

  • as the name of a procedure or procedure pointer
  • a procedure component of a derived type object
  • a type bound procedure binding name

The first can be seen as

procedure(), pointer :: sub_ptr=>sub
call sub()   ! With no argument list the parentheses are optional
call sub_ptr()

subroutine sub()
end subroutine

and the final two as

module mod
  type t
    procedure(sub), pointer, nopass :: sub_ptr=>sub
    procedure, nopass :: sub
  end type


  subroutine sub()
  end subroutine

end module

use mod
type(t) x
call x%sub_ptr()   ! Procedure component
call x%sub()       ! Binding name


For a procedure with dummy arguments the reference requires corresponding actual arguments, although optional dummy arguments may be not given.

Consider the subroutine

subroutine sub(a, b, c)
  integer a, b
  integer, optional :: c
end subroutine

This may be referenced in the following two ways

call sub(1, 2, 3)   ! Passing to the optional dummy c
call sub(1, 2)      ! Not passing to the optional dummy c

This is so-called positional referencing: the actual arguments are associated based on the position in the argument lists. Here, the dummy a is associated with 1, b with 2 and c (when specified) with 3.

Alternatively, keyword referencing may be used when the procedure has an explicit interface available

call sub(a=1, b=2, c=3)
call sub(a=1, b=2)

which is the same as the above.

However, with keywords the actual arguments may be offered in any order

call sub(b=2, c=3, a=1)
call sub(b=2, a=1)

Positional and keyword referencing may both be used

call sub(1, c=3, b=2)

as long as a keyword is given for every argument following the first appearance of a keyword

call sub(b=2, 1, 3)  ! Not valid: all keywords must be specified

The value of keyword referencing is particularly pronounced when there are multiple optional dummy arguments, as seen below if in the subroutine definition above b were also optional

call sub(1, c=3)  ! Optional b is not passed

The argument lists for type-bound procedures or component procedure pointers with a passed argument are considered separately.