Fortran Medium · Lesson 1 · On the house

Module privacy

private by default, public lists, protected variables, and clean APIs. Lesson 1 is free — on the house.

Lessons · Fortran Medium · Lesson 1 of 10 · On the house

Module privacy

private by default, public lists, protected variables, and clean APIs.

Illustration for Fortran
Lesson 1 is on the house.

Module entities are public by default. Write private on its own line to flip the default, then list the API: public :: stack_push, stack_pop.

protected module variables can be read by users but changed only inside the module, which gives read-only global state.

use m, only: a => alpha renames on import to avoid clashes between modules.

Keep helper procedures private so you can change them freely; only the public interface is a contract.

Private derived-type components (integer, private :: n) hide representation even when the type itself is public.

private/public

module counter_mod
  implicit none
  private
  public :: bump, count_value
  integer, protected, public :: total = 0
contains
  subroutine bump()
    total = total + step()
  end subroutine bump
  integer function count_value()
    count_value = total
  end function count_value
  integer function step()
    step = 1
  end function step
end module counter_mod

program main
  use counter_mod
  implicit none
  call bump(); call bump()
  print '(i0,1x,i0)', count_value(), total
end program main
Match this when you type.

Quiz

What does a lone private statement in a module do?

Quiz

What does protected allow outside the module?

Quiz

Can main call step()?

Quiz

What does the program print?

Check

Match the still for: Module privacy.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.