Reading — step 1 of 5
Learn
~2 min readSubroutines, Functions, Format I/O
Fortran has two kinds of subprograms:
function — returns a value
function square(x) result(r)
real, intent(in) :: x
real :: r
r = x * x
end function square
Key idioms:
result(name)— what's returned (can also use the function name)intent(in)— argument is read-only insideintent(out)— argument is set insideintent(inout)— both
The intent is documentation AND optimization hint — the compiler can skip aliasing checks.
subroutine — no return value, can have multiple out args
subroutine swap(a, b)
integer, intent(inout) :: a, b
integer :: tmp
tmp = a
a = b
b = tmp
end subroutine swap
Call with call swap(x, y) — call is mandatory.
Defining inside a program
program demo
implicit none
real :: r
r = square(5.0)
print *, r
contains ! marks where contained subprograms start
function square(x) result(r)
real, intent(in) :: x
real :: r
r = x * x
end function square
end program demo
The contains keyword separates the main program from internal subprograms. Internal subprograms can access the program's variables directly.
Recursion
Must mark the function recursive:
recursive function factorial(n) result(r)
integer, intent(in) :: n
integer :: r
if (n <= 1) then
r = 1
else
r = n * factorial(n - 1)
end if
end function factorial
Optional arguments
subroutine greet(name, prefix)
character(len=*), intent(in) :: name
character(len=*), intent(in), optional :: prefix
if (present(prefix)) then
print *, prefix, name
else
print *, "Hello, ", name
end if
end subroutine greet
present() checks whether the optional was supplied.
Array arguments
subroutine print_array(a)
integer, intent(in) :: a(:) ! assumed-shape — works for any size
integer :: i
do i = 1, size(a)
print *, a(i)
end do
end subroutine print_array
The (:) makes it an assumed-shape array. The compiler passes size info implicitly.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…