Procedures
Functions
Return a Result
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
subtotal ← 25
3integer :: subtotal, total4subtotal = 255total = add_tax(subtotal)values this step25subtotalcall ← add_tax(25)
4subtotal = 255total = add_tax(subtotal)6print '(I0)', totalvalues this stepadd_tax(25)call25subtotalout ← 27
10 integer :: out11 out = price + price / 1012end function add_taxvalues this step27out25pricetotal ← 27
4subtotal = 255total = add_tax(subtotal)6print '(I0)', totalvalues this step27totalprint '(I0)', total
5 total = add_tax(subtotal)6 print '(I0)', total7containsoutput27values this step27total
Follow the Function
subtotalstarts at25.total = add_tax(subtotal)sends25intoprice.- Inside the function,
price / 10uses integer division, so25 / 10becomes2. out = price + price / 10becomes25 + 2, so the returned value is27.- 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.