Variables in Fortran

Our first example demonstrates how to declare and use variables in Fortran. Here’s the full source code:

program variables
  implicit none
  
  ! Declare and initialize a character variable
  character(len=7) :: a = "initial"
  print *, a

  ! Declare and initialize multiple integer variables
  integer :: b = 1, c = 2
  print *, b, c

  ! Declare and initialize a logical variable
  logical :: d = .true.
  print *, d

  ! Declare an integer variable without initialization
  integer :: e
  print *, e

  ! Declare and initialize a character variable
  character(len=5) :: f = "apple"
  print *, f

end program variables

In Fortran, variables must be explicitly declared before they can be used. The implicit none statement at the beginning of the program turns off implicit typing, which is a good practice to avoid accidental variable declarations.

We can declare variables of different types:

  • character(len=7) :: a = "initial" declares a character variable of length 7 and initializes it.
  • integer :: b = 1, c = 2 declares two integer variables and initializes them.
  • logical :: d = .true. declares a logical variable and initializes it to true.
  • integer :: e declares an integer variable without initialization. In Fortran, uninitialized variables have undefined values, so it’s a good practice to always initialize variables before use.
  • character(len=5) :: f = "apple" declares another character variable and initializes it.

To run the program, save it as variables.f90 and compile it using a Fortran compiler, then run the resulting executable:

$ gfortran variables.f90 -o variables
$ ./variables
 initial
           1           2
 T
           0
 apple

Note that the output of uninitialized variables (like e in this case) is compiler-dependent and may not always be zero.

Fortran doesn’t have a direct equivalent to Go’s := syntax for declaring and initializing variables in one line within functions. In Fortran, variables are typically declared at the beginning of the program or subroutine.

Now that we’ve seen how to declare and use variables in Fortran, let’s move on to explore more features of the language.