032. Use parameter
s in modules to define constants#
topic: Modules
A physical or mathematical constant such as \(\pi\) that will be used
in many parts of a program should be defined as a parameter
in a
module that is use
d where needed.
In the code below, pi
is used both in module m
and the main program.
module constants_mod
implicit none
private
public :: pi
real, parameter :: pi = 3.14159
end module constants_mod
module m
use constants_mod, only: pi
implicit none
private
public :: area_circle
contains
real pure elemental function area_circle(radius) result(area)
real, intent(in) :: radius
area = pi*radius**2
end function area_circle
end module m
program main
use constants_mod, only: pi
use m, only: area_circle
implicit none
real, parameter :: radius = 10.0
print *, "circumference, area =", 2*pi*radius, area_circle(radius)
end program main
circumference, area = 62.8318024 314.158997
One should declare a module private
and list as public
the entities that will be referenced outside the module.
Module entities are public by default.
Created with @carbon_app pic.twitter.com/vWJuAwle97
— FortranTip (@fortrantip) December 20, 2021
- 1
Compiled using
GNU Fortran (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
with no flags