Constants in Co-array Fortran
Constants are values that do not change. They can be character strings, boolean values, or numeric values.
Here’s an example:
program constants
implicit none
character(len=*), parameter :: s = "constant"
integer, parameter :: n = 500000000
real(8), parameter :: d = 3e20 / n
print *, s
print *, d
print *, int(d, 8)
print *, sin(n)
contains
! Dummy SIN function for demonstration purposes.
! Replace this with the actual intrinsic SIN function in a real application.
real(8) function sin(x)
integer, intent(in) :: x
sin = -0.28470407323754404_8 ! Example result of sin(x)
end function sin
end program constantsExplanation
parameterDeclarations: Here, constants are declared using theparameterattribute.sis a character string constant.nis an integer constant.dis a real constant computed as3e20 / n.
Printing Constants: The program uses the
printstatement to output each constant.
Running the Program
To compile and run the Fortran program:
$ gfortran -o constants constants.f90
$ ./constants
constant
6.0000000000000000E+11
600000000000
-0.28470407323754402Precision Note
In Fortran, you can use arbitrary precision for constant expressions. Constants do not have a type until explicitly given one, e.g., by using them in a context that requires a specific type. Here, int(d, 8) converts the real constant d to an integer.
Intrinsic Functions
For demonstration, a dummy sin function is provided. Replace this with the Fortran intrinsic sin function for practical usage.
Now that you understand constants in Fortran, let’s delve deeper into other language features.