Fortran Modules

Fortran modules are used to define things for use in more than one subprogram (including the main program). Each module has a name, and a subprogram can gain access to items defined in that module with a use statement.

module constants
    ! Define ONLY constants here, not variables!
    ! (use the 'parameter' keyword)
    double precision, parameter :: &
        PI = 3.1415926535897932d0, &
        E = 2.7182818284590452d0, &
        TOLERANCE = 0.00000000001d0, &  ! For numerical methods
        AVOGADRO = 6.0221415d23         ! Not known to more digits than this
end module constants

! Main program body
program example
    use constants           ! Constants defined above

    ...
end program
        

Caution

Modules should be used only to define constants, not variables. Hence, each definition should include the parameter modifier.

Defining variables that can be modified by more than one subprogram will cause side effects. A side effect occurs when one subprogram modifies a variable and that change impacts the behavior of another subprogram. Issues caused by side effects are extremely difficult to debug, because it is impossible to tell by looking at a subprogram call what side effects it may cause. Hence, subprograms should only modify the values of variables that are passed to it as arguments, since these are visible in the call.

Defining constants in a module this way provides an alternative to using #define and the C preprocessor, which is non-standard in Fortran programming.

Practice

Note

Be sure to thoroughly review the instructions in Section 2, “Practice Problem Instructions” before doing the practice problems below.
  1. What do Fortran modules do?

  2. What kinds of things should and should not be defined in a module? Explain.