Skip to content
Subroutines and Functions
step 1/5

Reading — step 1 of 5

Learn

~1 min readModules and Subprograms

Fortran has two kinds of subprograms:

function — returns a value:

function square(n) result(s)
    integer, intent(in) :: n
    integer :: s
    s = n * n
end function

subroutine — like a void function, called with call:

subroutine swap(a, b)
    integer, intent(inout) :: a, b
    integer :: tmp
    tmp = a
    a = b
    b = tmp
end subroutine

!> Caller:
call swap(x, y)

intent declares parameter direction — caught at compile time:

  • intent(in) — read-only (most params)
  • intent(out) — output parameter, must be set
  • intent(inout) — read+write

Optional parameters:

function greet(name, greeting) result(msg)
    character(len=*), intent(in) :: name
    character(len=*), intent(in), optional :: greeting
    character(len=100) :: msg
    if (present(greeting)) then
        msg = greeting // ", " // name
    else
        msg = "Hello, " // name
    end if
end function

character(len=*) is the magic for accepting strings of any length.

Recursive functions — must declare recursive:

recursive function factorial(n) result(f)
    integer, intent(in) :: n
    integer(kind=8) :: f
    if (n <= 1) then
        f = 1
    else
        f = n * factorial(n - 1)
    end if
end function

Pure / elemental modifiers help the compiler optimize. pure means "no side effects." elemental means "works on each element of an array automatically."

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…