Procedures
Subroutines
Call With Side Effects
A subroutine updates its arguments through intent. call name(args) invokes it.
Program
Play the program to add a bonus into total through a subroutine.
subroutines.f90
Replay: real traced execution (multi-file project)
program subroutines_demo
implicit none
integer :: total
total = 10
call add_bonus(total, 5)
print '(I0)', total
contains
subroutine add_bonus(value, bonus)
integer, intent(inout) :: value
integer, intent(in) :: bonus
value = value + bonus
end subroutine add_bonus
end program subroutines_demo
total ← 10
3integer :: total4total = 105call add_bonus(total, 5)values this step10totalcall ← add_bonus(total, 5)
4total = 105call add_bonus(total, 5)6print '(I0)', totalvalues this stepadd_bonus(total, 5)call10totalvalue ← 15
10 integer, intent(in) :: bonus11 value = value + bonus12end subroutine add_bonusvalues this step10 → 15value5bonusprint '(I0)', total
5 call add_bonus(total, 5)6 print '(I0)', total7containsoutput15values this step15total
Follow the Update
totalstarts at10.call add_bonus(total, 5)sendstotaland bonus5into the subroutine.valueisintent(inout), so it can update the caller'stotal.value = value + bonusbecomes10 + 5.totalbecomes15, and the program prints15. | moment |totalorvalue| | --- | --- | | before call | 10 | | bonus | 5 | | aftervalue + bonus| 15 | | printed output | 15 |
subroutine
`subroutine add_bonus(...)` declares a callable with no return value.
call
`call add_bonus(...)` invokes the subroutine.
contains
`contains` introduces internal procedures inside a program.
Exercise: subroutines.f90
Reproduce the printed value 15, then change the bonus to 8 and predict the updated total before running it.