Variables in Co-array Fortran

Our first example demonstrates how to declare and use variables in Co-array Fortran. Variables are explicitly declared and used by the compiler to check type-correctness of operations.

program variables
  implicit none
  
  ! Declare and initialize a character variable
  character(len=7) :: a = "initial"
  print *, a
  
  ! Declare and initialize multiple variables at once
  integer :: b = 1, c = 2
  print *, b, c
  
  ! Logical variable
  logical :: d = .true.
  print *, d
  
  ! Variables declared without initialization are zero-valued
  integer :: e
  print *, e
  
  ! Character variable
  character(len=5) :: f = "apple"
  print *, f
end program variables

To run the program, save it as variables.f90 and compile it using a Co-array Fortran compiler:

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

Let’s break down the key points:

  1. In Co-array Fortran, we use implicit none to ensure all variables are explicitly declared.

  2. Variables are declared with their type and, optionally, their initial value.

  3. For character variables, we need to specify the length using character(len=X).

  4. Multiple variables of the same type can be declared and initialized in a single line.

  5. Logical variables use .true. and .false. for boolean values.

  6. Variables declared without initialization are automatically zero-valued (or the equivalent for their type).

  7. Co-array Fortran doesn’t have a shorthand syntax for variable declaration and initialization like Go’s :=. We always use the full declaration.

  8. The print * statement is used for output, similar to Go’s fmt.Println.

Co-array Fortran has strong typing and requires explicit variable declarations, which helps catch errors at compile-time and makes the code more self-documenting.