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
  1. total ← 10

    3integer :: total4total = 105call add_bonus(total, 5)
    values this step10total
  2. call ← add_bonus(total, 5)

    4total = 105call add_bonus(total, 5)6print '(I0)', total
    values this stepadd_bonus(total, 5)call10total
  3. value ← 15

    10    integer, intent(in) :: bonus11    value = value + bonus12end subroutine add_bonus
    values this step10 15value5bonus
  4. print '(I0)', total

    5    call add_bonus(total, 5)6    print '(I0)', total7contains
    output15
    values this step15total

Follow the Update

  1. total starts at 10.
  2. call add_bonus(total, 5) sends total and bonus 5 into the subroutine.
  3. value is intent(inout), so it can update the caller's total.
  4. value = value + bonus becomes 10 + 5.
  5. total becomes 15, and the program prints 15. | moment | total or value | | --- | --- | | before call | 10 | | bonus | 5 | | after value + 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.