Fortran offers two different procedures: function
and subroutine
. Subroutines are more general and offer the possibility to return multiple values whereas functions only return one value.
A subroutine
looks similar to a program
except that it also takes input parameters. It is invoked by a oneline command call
.
<keywords> subroutine <name> (<parameters>)
<statements>
end subroutine <name>
Subroutines must be invoked on separate lines by the call
command.
...
call <subroutine_name>(<parameters>)
...
Each parameter must have its intent
declared. The intent shows what the subroutine can do with each parameter. Possible intents are: in, out, inout
.
in
: The parameter will have an initial value and its value is not allowed to change.out
: The parameter will not have an initial value and one can set its value. The parameter retains the final value even after the procedure has ended.inout
(can also we written as in out
): An initial value is set and one can change its value. The parameter retains the final value even after the procedure has ended.Additionally, one can set the value
attribute. This allows the parameter to be changed inside of the procedure but the after its end the parameter will change back to its original value. This is useful for describing C functions.
Functions always return at most one value which can be of default type or derived type.
There are multiple ways to write identical functions. One method is
<keywords> function <func_name> (<parameters>) result (<res_name>)
<statements>
end function <func_name>
The variable res_name
has automatically the intent out
.
Functions can be invoked in the same manner as built-in functions, e.g. sin
. The following simplified example tries to show an invocation for a function some_function
which returns a real
value.
...
use some_module, only : some_function
real :: x = 1, y
y = x**3 + 3*x*some_function(x)
...
Only procedures with the keyword recursive
are permitted to call themselves.
For easy vectorization use the keyword elemental
. See also elemental.
The pure
keyword indicates that the procedure has no side effects, e.g. does not alter gloabl variables, or prints messages.