A function ... result(out) returns a value. The result clause names the return variable.

Program

Play the program to add tax to a subtotal with a function.

functions.f90
Replay: real traced execution (multi-file project)
program functions_demo
    implicit none
    integer :: subtotal, total
    subtotal = 25
    total = add_tax(subtotal)
    print '(I0)', total
contains
    function add_tax(price) result(out)
        integer, intent(in) :: price
        integer :: out
        out = price + price / 10
    end function add_tax
end program functions_demo
  1. subtotal ← 25

    3integer :: subtotal, total4subtotal = 255total = add_tax(subtotal)
    values this step25subtotal
  2. call ← add_tax(25)

    4subtotal = 255total = add_tax(subtotal)6print '(I0)', total
    values this stepadd_tax(25)call25subtotal
  3. out ← 27

    10    integer :: out11    out = price + price / 1012end function add_tax
    values this step27out25price
  4. total ← 27

    4subtotal = 255total = add_tax(subtotal)6print '(I0)', total
    values this step27total
  5. print '(I0)', total

    5    total = add_tax(subtotal)6    print '(I0)', total7contains
    output27
    values this step27total

Follow the Function

  1. subtotal starts at 25.
  2. total = add_tax(subtotal) sends 25 into price.
  3. Inside the function, price / 10 uses integer division, so 25 / 10 becomes 2.
  4. out = price + price / 10 becomes 25 + 2, so the returned value is 27.
  5. The program prints 27. | value | result | | --- | --- | | subtotal | 25 | | price / 10 | 2 | | out | 27 | | printed output | 27 |
function `function name(args) result(out)` returns a value.
intent(in) `intent(in)` marks an argument read-only.
result clause `result(out)` names the variable that holds the return.

Exercise: functions.f90

Reproduce the printed value 27, then change subtotal to 40 and predict the tax-added total before running it.