Syntax of a (non-recursive) function:
[hereprefix
] FUNCTION
procname
( [
dummy args
])
declaration of dummy args
![]()
declaration of local objects
![]()
...
executable stmts, assignment of result
![]()
[ CONTAINS
internal procedure definitions
]
END [ FUNCTION [
procname
] ]
FUNCTIONprocname
( [
dummy args
])
declaration of dummy args
![]()
declaration of procname type
![]()
declaration of local objects
![]()
...
executable stmts, assignment of result
![]()
[ CONTAINS
internal procedure definitions
]
END [ FUNCTION [
procname
] ]
Functions are very similar to subroutines except that a function should have a type specifier which defines the type of the result. (The type of the function result can either be given as a prefix to the function name or alternatively be given in the declarations area of the code by preceding the function name (with no arguments or parentheses) by a type specifier. It is a matter of personal taste which method is adopted.) For example,
INTEGER FUNCTION largest(i,j,k) IMPLICIT NONE
is equivalent to,
FUNCTION largest(i,j,k) IMPLICIT NONE INTEGER largest
The function name,
procname
, is the result variable so a function must contain a statement
which assigns a value to this name; a routine without one is an error.
The type of an external function must be given in the calling program unit. It is good practise to attribute this declaration with the EXTERNAL attribute. A valid declaration in the calling program unit might be,
INTEGER, EXTERNAL :: largest
Functions can return results of any type, kind and rank (including
user defined types and pointers) and, as with subroutines,
RECURSIVE functions must be explicitly declared (see Section
).
Note that due to the possibility of confusion between an array reference and a function reference the parentheses are not optional.