Consider the following example,
PROGRAM Thingy IMPLICIT NONE ..... PRINT*, F(a,b) ..... CONTAINS REAL FUNCTION F(x,y) REAL, INTENT(IN) :: x,y F = SQRT(x*x + y*y) END SUBROUTINE OutputFigures END PROGRAM Thingy
Functions operate on the same principle to SUBROUTINE s, the only difference being that a function returns a value. In the example, the line
PRINT*, F(a,b)
will substitute the value returned by the function for F(a,b)
, in
other words, the value of .
Just like subroutines, functions also lie between CONTAINS and END PROGRAM statements. They have the following syntax:
[< prefix >] FUNCTION < procname >( [< dummyargs >])< declaration of dummy args >
< declaration of local objects >
...
< executable stmts, assignment of result >
END [ FUNCTION [ < procname > ] ]
It is also possible to declare the function type in the declarations area instead of in the header:
FUNCTION < procname >( [< dummy args >])< declaration of dummy args >
< declaration of result type >
< declaration of local objects >
...
< executable stmts, assignment of result >
END [ FUNCTION [ < procname > ] ]
This would mean that the above function could be equivalently declared as:
FUNCTION F(x,y) REAL :: F REAL, INTENT(IN) :: x,y F = SQRT(x*x + y*y) END SUBROUTINE OutputFigures
(Recall that not all HPF compilers implement internal functions.)
Functions may also be recursive, see Section 14.6, and may be either scalar or array valued (including user defined types and pointers). Note that due to the possibility of confusion between an array reference and a function reference the parentheses are not optional.
Return to corresponding overview page