TExcelTAD
Home › Fortran › Fortran Subroutines & intent

Fortran Subroutines & intent

A subroutine is a procedure that does not return a value. You run it with call, and it passes results back by modifying its arguments. Use a subroutine when a procedure has several outputs, changes data in place, or performs an action such as printing.

fortran · try it yourself
program use_subroutine
  implicit none
  call greet('Ada', 3)
  call greet('Linus', 1)

contains

  subroutine greet(name, times)
    character(len=*), intent(in) :: name
    integer, intent(in) :: times
    integer :: i
    do i = 1, times
      print '(a, a, a)', 'Hello, ', name, '!'
    end do
  end subroutine greet

end program use_subroutine
Hello, Ada!
Hello, Ada!
Hello, Ada!
Hello, Linus!

character(len=*) means the dummy argument takes its length from the actual argument, so the subroutine works with strings of any length.

Arguments are passed by reference

Fortran passes arguments by reference: the dummy argument is another name for the caller's variable. Changing it inside the subroutine changes the caller's variable:

fortran · try it yourself
program by_reference
  implicit none
  real :: a = 1.0, b = 2.0
  print '(a, 2f5.1)', 'before:', a, b
  call swap(a, b)
  print '(a, 2f5.1)', 'after: ', a, b

contains

  subroutine swap(x, y)
    real, intent(inout) :: x, y
    real :: tmp
    tmp = x
    x = y
    y = tmp
  end subroutine swap

end program by_reference
before:  1.0  2.0
after:   2.0  1.0

intent: in, out, inout

The intent attribute documents, and lets the compiler check, how each argument is used:

Intent The procedure… The caller must pass…
intent(in) only reads it; assigning to it is a compile error any expression
intent(out) must set it; its value on entry is undefined a variable
intent(inout) reads and modifies it a variable with a defined value

Always give every argument an intent. The compiler then catches mistakes such as modifying an input:

fortran · try it yourself
program intent_check
  implicit none
  real :: x = 4.0
  call scale(x)
  print *, x

contains

  subroutine scale(v)
    real, intent(in) :: v
    v = v * 2.0           ! not allowed: v is intent(in)
  end subroutine scale

end program intent_check
/app/example.f90:11:5:

   11 |     v = v * 2.0           ! not allowed: v is intent(in)
      |     1~
Error: Dummy argument 'v' with INTENT(IN) in variable definition context (assignment) at (1)

Several outputs

A subroutine is the natural choice when a calculation produces more than one result:

fortran · try it yourself
program statistics
  implicit none
  real :: data(8) = [4.0, 8.0, 15.0, 16.0, 23.0, 42.0, 7.0, 9.0]
  real :: mean, std_dev, low, high

  call describe(data, mean, std_dev, low, high)
  print '(a, f7.3)', 'mean:    ', mean
  print '(a, f7.3)', 'std dev: ', std_dev
  print '(a, 2f7.2)', 'range:   ', low, high

contains

  subroutine describe(x, mean, sd, lo, hi)
    real, intent(in)  :: x(:)
    real, intent(out) :: mean, sd, lo, hi
    integer :: n
    n = size(x)
    mean = sum(x) / n
    sd = sqrt(sum((x - mean)**2) / (n - 1))   ! sample standard deviation
    lo = minval(x)
    hi = maxval(x)
  end subroutine describe

end program statistics
mean:     15.500
std dev:  12.317
range:      4.00  42.00

Modifying arrays in place

Arrays are also passed by reference, so a subroutine can update a large array without copying it:

fortran · try it yourself
program in_place
  implicit none
  integer :: values(7) = [29, 3, 17, 8, 42, 1, 15]
  call bubble_sort(values)
  print '(*(i4))', values

contains

  subroutine bubble_sort(a)
    integer, intent(inout) :: a(:)
    integer :: i, j, tmp
    logical :: swapped
    do i = size(a) - 1, 1, -1
      swapped = .false.
      do j = 1, i
        if (a(j) > a(j + 1)) then
          tmp = a(j); a(j) = a(j + 1); a(j + 1) = tmp
          swapped = .true.
        end if
      end do
      if (.not. swapped) exit
    end do
  end subroutine bubble_sort

end program in_place
   1   3   8  15  17  29  42

The intent(out) trap

On entry to the subroutine, an intent(out) argument is undefined (and an allocatable intent(out) argument is deallocated). Don't read it before assigning it:

fortran
subroutine accumulate(total, x)
  real, intent(out) :: total   ! WRONG: should be intent(inout)
  real, intent(in) :: x
  total = total + x            ! reads an undefined value
end subroutine accumulate

Leaving early: return

return ends a subroutine (or function) immediately. It's useful for guard clauses:

fortran
subroutine safe_divide(a, b, q, ok)
  real, intent(in) :: a, b
  real, intent(out) :: q
  logical, intent(out) :: ok
  ok = (b /= 0.0)
  q = 0.0
  if (.not. ok) return
  q = a / b
end subroutine safe_divide

Test yourself

How is a subroutine named update invoked?

  1. update(x)
  2. call update(x)
  3. x = update()
  4. run update(x)

Which intent should an argument have that the procedure both reads and modifies?

  1. intent(in)
  2. intent(out)
  3. intent(inout)
  4. No intent

What is the value of an intent(out) scalar argument when the subroutine starts?

  1. Zero
  2. The caller's value
  3. Undefined
  4. Always -1