TExcelTAD
Home › Fortran › Fortran Functions

Fortran Functions

Fortran has two kinds of procedures: functions, which return a value and are used inside expressions, and subroutines, which are invoked with call and communicate through their arguments. This lesson covers functions; subroutines come next.

A first function

The simplest place to put a procedure is after contains at the end of the main program. Such an internal procedure can be used anywhere in that program.

fortran · try it yourself
program circle
  implicit none
  print '(a, f8.4)', 'area(1.0) = ', area(1.0)
  print '(a, f8.4)', 'area(2.5) = ', area(2.5)
  print '(a, f8.4)', 'ring area = ', area(3.0) - area(2.0)

contains

  function area(radius) result(a)
    real, intent(in) :: radius     ! the argument
    real :: a                      ! the result variable
    real, parameter :: pi = 3.14159265
    a = pi * radius**2
  end function area

end program circle
area(1.0) =   3.1416
area(2.5) =  19.6350
ring area =  15.7080

The parts of a function:

Part Meaning
function area(radius) name and list of dummy arguments
result(a) names the variable whose final value is returned
real, intent(in) :: radius declares each argument; intent(in) promises not to change it
real :: a declares the result's type
end function area ends the function

Without result(...) the function's own name acts as the result variable (area = pi * radius**2). Both styles are common; result is required for recursive functions and makes code clearer, so this course uses it.

The result type in the header

The result type can also be written in front of function. This form is compact for short functions:

fortran · try it yourself
program shorthand
  implicit none
  print '(i0)', cube(4)
  print '(l1)', is_even(7)

contains

  integer function cube(n)
    integer, intent(in) :: n
    cube = n**3
  end function cube

  logical function is_even(n)
    integer, intent(in) :: n
    is_even = mod(n, 2) == 0
  end function is_even

end program shorthand
64
F

Several arguments and local variables

Variables declared inside a function are local: they exist only while it runs and can't clash with names elsewhere.

fortran · try it yourself
program bmi_calc
  use iso_fortran_env, only: real64
  implicit none
  integer, parameter :: dp = real64

  print '(a, f5.1)', 'BMI: ', bmi(72.0_dp, 1.80_dp)
  print '(a, f6.2, a)', 'distance: ', distance(0.0_dp, 0.0_dp, 3.0_dp, 4.0_dp), ' km'

contains

  function bmi(mass_kg, height_m) result(index)
    real(dp), intent(in) :: mass_kg, height_m
    real(dp) :: index
    index = mass_kg / height_m**2
  end function bmi

  function distance(x1, y1, x2, y2) result(d)
    real(dp), intent(in) :: x1, y1, x2, y2
    real(dp) :: d
    real(dp) :: dx, dy             ! locals
    dx = x2 - x1
    dy = y2 - y1
    d = sqrt(dx**2 + dy**2)
  end function distance

end program bmi_calc
BMI:  22.2
distance:   5.00 km

Note: Arguments are matched by position, and their types must match exactly. Passing a default real literal 72.0 where a real(dp) is expected is a compile error when the interface is known, as it is for internal and module procedures. That strictness catches real bugs.

Functions returning arrays

A function can return an array whose size depends on its arguments:

fortran · try it yourself
program array_result
  implicit none
  integer :: i
  print '(*(i5))', fibonacci(12)
  print '(*(f6.2))', normalise([2.0, 3.0, 5.0])

contains

  function fibonacci(n) result(f)
    integer, intent(in) :: n
    integer :: f(n)
    integer :: k
    f(1) = 1
    if (n > 1) f(2) = 1
    do k = 3, n
      f(k) = f(k - 1) + f(k - 2)
    end do
  end function fibonacci

  function normalise(v) result(w)
    real, intent(in) :: v(:)       ! assumed shape: any length
    real :: w(size(v))
    w = v / sum(v)
  end function normalise

end program array_result
    1    1    2    3    5    8   13   21   34   55   89  144
  0.20  0.30  0.50

v(:) is an assumed-shape array argument: the function accepts an array of any size and asks for it with size(v).

Side effects: keep functions pure in spirit

A function may modify its arguments or print, but that makes code hard to reason about, and because the compiler may evaluate parts of an expression in any order (or skip a call whose value isn't needed), side effects in functions are risky. Good practice:

  • give every function argument intent(in);
  • don't print or change global variables in functions;
  • use a subroutine when a procedure needs to modify things.

The pure attribute (covered later) lets the compiler enforce these rules.

Test yourself

What does result(r) in a function header do?

  1. Prints r when the function ends
  2. Names the variable whose value is returned
  3. Declares r as a global
  4. Makes the function recursive

Where do internal procedures go in a main program?

  1. Before program
  2. After contains, before end program
  3. Inside a do loop
  4. In a separate file only

What does real, intent(in) :: v(:) declare?

  1. A scalar argument
  2. An assumed-shape 1-D array argument of any length
  3. An allocatable local array
  4. A zero-length array