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 constants

Explanation

  1. parameter Declarations: Here, constants are declared using the parameter attribute.

    • s is a character string constant.
    • n is an integer constant.
    • d is a real constant computed as 3e20 / n.
  2. Printing Constants: The program uses the print statement 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.28470407323754402

Precision 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.