Constants in Fortran

Go supports constants of character, string, boolean, and numeric values.

A const declaration defines a constant value.

Here’s an example of defining and using constants:

program ConstantsExample
    implicit none
    character(len=*), parameter :: s = "constant"
    integer, parameter :: n = 500000000
    real(8), parameter :: d = 3.0E20 / n

    print *, s
    print *, d
    print *, int(d, 8)
    print *, sin(n)
end program ConstantsExample

In this example:

  • s is a string constant with the value “constant”.
  • n is an integer constant with the value 500000000.
  • d is a real constant obtained by dividing 3.0E20 by n.
  • The int(d, 8) function converts the real value d to an integer.
  • The sin(n) function calculates the sine of n and prints it.

To run the program, compile the code and then execute it.

$ gfortran -o ConstantsExample ConstantsExample.f90
$ ./ConstantsExample
 constant
   6.000000000000000E+11
                600000000000
  -0.284704073237544

Constants are used the same way variables are, but their values cannot be changed once defined.

Now that we understand the use of constants in Fortran, let’s explore more features of the language.