Fortran Function syntax


Example

Functions can be written using several types of syntax

function name()
  integer name
  name = 42
end function
integer function name()
  name = 42
end function
function name() result(res)
  integer res
  res = 42
end function

Functions return values through a function result. Unless the function statement has a result clause the function's result has the same name as the function. With result the function result is that given by the result. In each of the first two examples above the function result is given by name; in the third by res.

The function result must be defined during execution of the function.

Functions allow to use some special prefixes.

Pure function means that this function has no side effect:

pure real function square(x)
  real, intent(in) :: x
  square = x * x
end function

Elemental function is defined as scalar operator but it can be invoked with array as actual argument in which case the function will be applied element-wise. Unless the impure prefix (introduced in Fortran 2008) is specified an elemental function is also a pure function.

elemental real function square(x)
  real, intent(in) :: x
  square = x * x
end function