Fortran Procedures - Functions and Subroutines Function syntax

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any Fortran Question?