Fortran Procedure Arguments
Fortran procedures have a flexible argument system: keyword arguments, optional arguments, and several ways to pass arrays and strings. Getting these right makes procedures pleasant to call and safe to use.
Keyword arguments
Any argument can be passed by name using the dummy argument's name. Keyword arguments may appear in any order, after the positional ones:
program keywords
implicit none
print '(f8.2)', compound(principal=1000.0, rate=0.05, years=10)
print '(f8.2)', compound(1000.0, years=10, rate=0.05)
print '(f8.2)', compound(500.0, 0.03, 20)
contains
function compound(principal, rate, years) result(amount)
real, intent(in) :: principal, rate
integer, intent(in) :: years
real :: amount
amount = principal * (1.0 + rate)**years
end function compound
end program keywords 1628.89
1628.89
903.06
Keywords make calls with many numeric arguments self-documenting: solve(tolerance=1e-8, max_iter=100) is much clearer than solve(1e-8, 100).
Optional arguments
An argument declared optional may be left out. Inside the procedure, present(arg) tells you whether it was passed. You must not use an absent argument, so the usual pattern copies it into a local variable with a default:
program optional_args
implicit none
call log_message('Simulation started')
call log_message('Low memory', level='WARN')
call log_message('Step done', step=42)
call log_message('Diverged', level='ERROR', step=97)
contains
subroutine log_message(text, level, step)
character(len=*), intent(in) :: text
character(len=*), intent(in), optional :: level
integer, intent(in), optional :: step
character(len=:), allocatable :: lvl
lvl = 'INFO'
if (present(level)) lvl = level
if (present(step)) then
print '(a, a, a, i0, a, a)', '[', lvl, '] step ', step, ': ', text
else
print '(a, a, a, a)', '[', lvl, '] ', text
end if
end subroutine log_message
end program optional_args[INFO] Simulation started
[WARN] Low memory
[INFO] step 42: Step done
[ERROR] step 97: Diverged
Optional arguments usually come last; when you skip one in the middle, pass the following ones by keyword.
Note: Optional and keyword arguments require an explicit interface: the caller must know the procedure's argument list. That's automatic for internal procedures and module procedures (the next lesson), which is one more reason to put procedures in modules.
Passing arrays
There are three common ways to declare an array dummy argument:
| Declaration | Name | Size comes from |
|---|---|---|
real :: a(:) |
assumed shape | the actual argument (recommended) |
real :: a(n) |
explicit shape | another argument n |
real :: a(*) |
assumed size | nobody knows (legacy, avoid) |
program array_args
implicit none
real :: v(5) = [1.0, 2.0, 3.0, 4.0, 5.0]
real :: m(2, 3) = reshape([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [2, 3])
print '(f6.2)', mean(v)
print '(f6.2)', mean(v(2:4)) ! sections work too
print '(f6.2)', mean(v(::2)) ! even strided ones
print '(f6.2)', weighted(v, [1.0, 0.0, 0.0, 0.0, 1.0], 5)
call show_shape(m)
call show_shape(m(:, 2:3))
contains
function mean(x) result(r)
real, intent(in) :: x(:) ! assumed shape
real :: r
r = sum(x) / size(x)
end function mean
function weighted(x, w, n) result(r)
integer, intent(in) :: n
real, intent(in) :: x(n), w(n) ! explicit shape
real :: r
r = sum(x * w) / sum(w)
end function weighted
subroutine show_shape(a)
real, intent(in) :: a(:, :)
print '(a, i0, a, i0)', 'rows: ', size(a, 1), ', cols: ', size(a, 2)
end subroutine show_shape
end program array_args 3.00
3.00
3.00
3.00
rows: 2, cols: 3
rows: 2, cols: 2
Tip: An assumed-shape dummy argument always starts at index 1 inside the procedure, whatever the bounds of the actual argument. Write
real :: a(0:)to make it start at 0 instead.
Allocatable dummy arguments
A dummy argument can itself be allocatable. The procedure can then allocate or resize the caller's array, which is useful when the procedure decides how many results there are:
program alloc_arg
implicit none
integer, allocatable :: divs(:)
call divisors(36, divs)
print '(a, i0, a, *(i0, 1x))', 'divisors of 36 (', size(divs), '): ', divs
call divisors(13, divs)
print '(a, i0, a, *(i0, 1x))', 'divisors of 13 (', size(divs), '): ', divs
contains
subroutine divisors(n, d)
integer, intent(in) :: n
integer, allocatable, intent(out) :: d(:) ! deallocated on entry
integer :: k
allocate(d(0))
do k = 1, n
if (mod(n, k) == 0) d = [d, k]
end do
end subroutine divisors
end program alloc_argdivisors of 36 (9): 1 2 3 4 6 9 12 18 36
divisors of 13 (2): 1 13
The value attribute
value makes the procedure work on a copy of the argument. It can then modify the copy freely without affecting the caller. It is also essential for C interoperability:
program value_attr
implicit none
integer :: n = 5
print '(a, i0)', 'digits summed: ', digit_sum(98765)
call countdown(n)
print '(a, i0)', 'n is still ', n
contains
integer function digit_sum(m)
integer, value :: m ! local copy, safe to modify
digit_sum = 0
do while (m > 0)
digit_sum = digit_sum + mod(m, 10)
m = m / 10
end do
end function digit_sum
subroutine countdown(k)
integer, value :: k
do while (k > 0)
write(*, '(i0, 1x)', advance='no') k
k = k - 1
end do
print '(a)', 'liftoff'
end subroutine countdown
end program value_attrdigits summed: 35
5 4 3 2 1 liftoff
n is still 5
Test yourself
How can a procedure check whether an optional argument tol was passed?
if (tol /= 0)if (present(tol))if (allocated(tol))if (associated(tol))
What is the lower bound of an assumed-shape dummy x(:) when the caller passes a(5:9)?
- 5
- 1
- 0
- 9
Which call is valid for subroutine s(a, b, c) with all three arguments?
call s(c=3, 1, 2)call s(1, c=3, b=2)call s(a=1, 2, 3)call s(b=2, 1, 3)