Fortran Modern alternatives to historical features Statement functions


Example

Consider the program

implicit none
integer f, i
f(i)=i

print *, f(1)
end

Here f is a statement function. It has integer result type, taking one integer dummy argument.1

Such a statement function exists within the scope in which it is defined. In particular, it has access to variables and named constants accessible in that scope.

However, statement functions are subject to many restrictions and are potentially confusing (looking at casual glance like an array element assignment statement). Important restrictions are:

  • the function result and dummy arguments must be scalar
  • the dummy arguments are in the same scope as the function
  • statement functions have no local variables
  • statement functions cannot be passed as actual arguments

The main benefits of statement functions are repeated by internal functions

implicit none

print *, f(1)

contains

  integer function f(i)
    integer i
    f = i
  end function

end

Internal functions are not subject to the restrictions mentioned above, although it is perhaps worth noting that an internal subprogram may not contain further internal subprogram (but it may contain a statement function).

Internal functions have their own scope but also have available host association.


1 In real old code examples, it wouldn't be unusual to see the dummy arguments of a statement function being implicitly typed, even if the result has explicit type.