Fortran Wiki
Sandbox

Procedures

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.

Subroutine

A subroutine looks similar to a program except that it also takes input parameters. It is invoked by a oneline command call.

Outline

<keywords> subroutine <name> (<parameters>)
  <statements>  
end subroutine <name>

Invocation

Subroutines must be invoked on separate lines by the call command.

...
  call <subroutine_name>(<parameters>)
...

Parameter intents

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.

Function

Functions always return at most one value which can be of default type or derived type.

Outline

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.

Invocation

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)
...

Keywords

Recursive

Only procedures with the keyword recursive are permitted to call themselves.

Elemental

For easy vectorization use the keyword elemental. See also elemental.

Pure

The pure keyword indicates that the procedure has no side effects, e.g. does not alter gloabl variables, or prints messages.

Module

Modules are used for object oriented programming.

General form

The general form is

module <name>
  <use statements>  
  <declarations>
contains
  <subroutines and functions>
end module <name>