Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 39 ยท Procedures and Modules

Subroutines and Functions in Fortran

Learn how Fortran splits work into functions and subroutines: the result clause, call statements, internal procedures, and how arguments are passed by reference.

Real programs are never one long block of statements. Fortran gives you two kinds of procedures to break work into named pieces: functions, which return a single value and are used inside expressions, and subroutines, which are invoked with call and can hand back any number of results through their arguments. This chapter builds from these two ideas to modules, interfaces and recursion.

Fortran was designed for numerical work, so its procedure rules are tuned for it: arguments are passed by reference, arrays travel without copying, and the compiler can check a lot of what you wrote. Understanding those rules early saves a great deal of debugging later.

The Fortran compiler is not available on this site, so the Fortran code blocks in this chapter are read-only. Where a lesson shows behavior you can try, a small Python stand-in is runnable and is clearly labelled as a stand-in.

Functions

A function computes one value. You declare its type, name its dummy arguments, and assign the answer to the function's result:

FORTRAN
program area_demo
  implicit none
  real :: r

  r = 2.5
  print *, "Circle area:", circle_area(r)

contains

  real function circle_area(radius)
    real, intent(in) :: radius
    real, parameter :: pi = 3.14159265
    circle_area = pi * radius**2
  end function circle_area

end program area_demo

Three things to notice. The procedure lives after contains inside the program, so it is an internal procedure and automatically sees the program's other names. The type of the result (real) is written in front of function. And the value is returned by assigning to the function's own name, circle_area.

The result clause

When a function name is long, or the function calls itself, it is cleaner to name the result variable separately:

FORTRAN
function mean(values, n) result(m)
  integer, intent(in) :: n
  real, intent(in) :: values(n)
  real :: m
  m = sum(values) / real(n)
end function mean

Now m is the variable you assign, and mean is only the name callers use. Most modern Fortran code uses result(...), and recursive functions require it (see recursion and pure procedures).

Subroutines

A subroutine does not return a value. It does something, and communicates results by changing its arguments:

FORTRAN
subroutine min_max(a, n, lo, hi)
  integer, intent(in)  :: n
  real,    intent(in)  :: a(n)
  real,    intent(out) :: lo, hi
  lo = minval(a)
  hi = maxval(a)
end subroutine min_max

You run it with call:

FORTRAN
real :: data(5) = [4.0, 1.5, 9.0, 3.2, 7.7]
real :: smallest, largest
call min_max(data, 5, smallest, largest)
print *, smallest, largest

Use a function when the answer is one value you want inside an expression, and a subroutine when you return several values or mainly cause a side effect (printing, writing a file, filling an array).

Function or subroutine?

Function One result, used in an expression
Subroutine Invoked with call, results through arguments

Both can be internal, in a module, or external

1 / 2

Arguments are passed by reference

In Fortran the procedure receives the address of your variable, not a copy. If a subroutine changes a dummy argument, the caller's variable changes too. That is efficient for large arrays, but it means a mistake can corrupt data far from the bug. The intent attribute, covered in the next lesson (argument intent and optional arguments), lets the compiler catch such mistakes.

The stand-in below mimics reference semantics with a Python list: the callee mutates the object the caller owns, exactly like a Fortran array dummy argument.

Python Stand-in: reference semantics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Where procedures can live

There are three places to put a procedure:

Placement How When to use
Internal after contains inside a program or procedure small helpers used only there
Module after contains inside a module almost everything: reusable, with compiler-checked interfaces
External a separate file with no module legacy code only

External procedures have an implicit interface: the compiler cannot check that the actual arguments match what the procedure expects. That is the cause of countless old bugs. Prefer modules (see modules and use).

flowchart TD
    A["program"] --> B["contains: internal procedures"]
    A --> C["use module"]
    C --> D["module procedures<br/>explicit interface"]
    A -.-> E["external procedure<br/>implicit interface (avoid)"]

Internal and module procedures give the compiler the information it needs to check calls.

Functions with array arguments

A function may take arrays and return a scalar, or even return an array:

FORTRAN
function normalize(v) result(w)
  real, intent(in) :: v(:)
  real :: w(size(v))
  w = v / sqrt(sum(v**2))
end function normalize

v(:) is an assumed-shape dummy argument: it takes its size from the actual argument, and size(v) recovers it. This form needs an explicit interface, which is one more reason to put the function in a module or after contains.

Common mistakes

  • Forgetting implicit none. Without it a typo such as radus silently creates a new variable.
  • Calling a subroutine without call, or a function with call.
  • Not assigning the result: a function whose result is never set returns garbage.
  • Passing a literal constant to a dummy argument that the procedure modifies. call scale_in_place(2.0, f) with an intent(inout) dummy is an error the compiler can catch.
  • Writing a function that changes its arguments as a side effect. Keep functions clean, and use pure (see recursion and pure procedures).
Python Stand-in: function vs subroutine style

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you run a subroutine?

    Subroutines are invoked with the call statement. Functions are used inside expressions.
  2. 2. How does a function with a result(m) clause return its value?

    You assign to the variable named in result(). Fortran has a plain return statement but it does not carry a value.
  3. 3. What does pass-by-reference mean for a Fortran dummy argument?

    The callee sees the same memory as the caller, so changes to a dummy argument change the actual argument.
  4. 4. Which placement gives the compiler an explicit interface?

    Module and internal procedures have explicit interfaces, so argument mismatches are caught at compile time.

Summary

  • A function returns one value and is used in expressions; a subroutine uses call and returns data through arguments.
  • Name the result with result(name) for clarity and for recursion.
  • Arguments are passed by reference, so a callee can change the caller's data.
  • Internal and module procedures have explicit interfaces; external ones do not.
  • Assumed-shape arrays (v(:)) take their size from the caller.

Next: Argument intent and optional arguments