Functions in Fortran

Functions are central in Fortran. We’ll learn about functions with a few different examples.

program main
    implicit none
    integer :: result

    ! Call a function just as you'd expect, with name(args).
    result = plus(1, 2)
    print *, "1+2 =", result

    result = plus_plus(1, 2, 3)
    print *, "1+2+3 =", result

contains

    ! Here's a function that takes two integers and returns
    ! their sum as an integer.
    function plus(a, b)
        integer, intent(in) :: a, b
        integer :: plus
        plus = a + b
    end function plus

    ! In Fortran, we can define multiple parameters of the same type
    ! in a single declaration.
    function plus_plus(a, b, c)
        integer, intent(in) :: a, b, c
        integer :: plus_plus
        plus_plus = a + b + c
    end function plus_plus

end program main

To compile and run the Fortran program:

$ gfortran functions.f90 -o functions
$ ./functions
1+2 = 3
1+2+3 = 6

Here’s a breakdown of the Fortran code:

  1. In Fortran, we define the main program using the program keyword.

  2. The implicit none statement is used to require explicit declaration of all variables.

  3. Functions in Fortran are defined using the function keyword, followed by the function name and its parameters.

  4. The intent(in) attribute specifies that the parameters are input-only and won’t be modified within the function.

  5. In Fortran, the function name itself acts as the return variable. We assign the result to the function name before the end of the function.

  6. The contains keyword is used to include internal procedures (functions and subroutines) within the main program.

  7. To call a function, we use the syntax function_name(args), similar to many other programming languages.

There are several other features to Fortran functions. One is the ability to return multiple values using subroutines, which we’ll look at next.