Subroutines and functions
Subroutines
A subroutine is a reusable block that works through its arguments: it takes inputs, does work, and returns results through the same variables.
Internal procedures after contains carry an explicit interface, so the compiler checks every call for you.
program subdemo
implicit none
integer :: x
x = 5
call double_it(x)
print *, x
contains
subroutine double_it(n)
implicit none
integer, intent(inout) :: n
n = n * 2
end subroutine double_it
end program subdemo
./subdemo
10
Functions return values
A function returns one value through its own name: assign to the function name inside, and the caller receives the result in an expression.
The return type stands in front of the function keyword, which keeps the contract visible at a glance.
program funcdemo
implicit none
print *, square(6)
contains
integer function square(x)
implicit none
integer, intent(in) :: x
square = x * x
end function square
end program funcdemo
./funcdemo
36
Call them
Call runs a subroutine with call plus arguments, while a function is used inside an expression where its value is needed.
Actual arguments must match the dummies in count, type, and order, and the explicit interface verifies all three.
program calldemo
implicit none
integer :: a
integer :: b
a = 3
b = 4
call swap_vals(a, b)
print *, a, b
contains
subroutine swap_vals(x, y)
implicit none
integer, intent(inout) :: x
integer, intent(inout) :: y
integer :: tmp
tmp = x
x = y
y = tmp
end subroutine swap_vals
end program calldemo
./calldemo
4 3
Mark pure
Pure procedures promise no side effects: no writes to global state and no IO, which lets callers and optimizers trust them fully.
Mark helpers pure when they only compute from inputs: the compiler then enforces the promise for you.
program puredemo
implicit none
integer :: v(3)
v = [1, 2, 3]
print *, total(v)
contains
pure integer function total(a)
implicit none
integer, intent(in) :: a(3)
total = sum(a)
end function total
end program puredemo
./puredemo
6
The code on this page was run with gfortran 15.2.0 on Alpine Linux 3.24 (x86_64) in a Docker container.
Article author: Arthur Isaev