Functions in Co-array Fortran

Functions are central in Co-array Fortran. We’ll learn about functions with a few different examples.

module functions_module
  implicit none

contains
  ! Here's a function that takes two integers and returns
  ! their sum as an integer.
  function plus(a, b) result(sum)
    integer, intent(in) :: a, b
    integer :: sum
    sum = a + b
  end function plus

  ! In Co-array Fortran, we can define functions with multiple
  ! parameters of the same type in a more concise way.
  function plus_plus(a, b, c) result(sum)
    integer, intent(in) :: a, b, c
    integer :: sum
    sum = a + b + c
  end function plus_plus

end module functions_module

program main
  use functions_module
  implicit none

  integer :: res

  ! Call a function as you'd expect, with name(args).
  res = plus(1, 2)
  print *, "1+2 =", res

  res = plus_plus(1, 2, 3)
  print *, "1+2+3 =", res

end program main

To compile and run this Co-array Fortran program:

$ gfortran -coarray=single functions.f90 -o functions
$ ./functions
 1+2 =           3
 1+2+3 =           6

In Co-array Fortran:

  1. Functions are typically defined within modules for better organization and scope control.
  2. The result keyword is used to specify the name of the return value.
  3. The intent(in) attribute is used to indicate that the function parameters are input-only and won’t be modified.
  4. Unlike some languages, Fortran doesn’t require explicit return statements. The result variable is automatically returned at the end of the function.
  5. The contains statement is used to separate the module’s interface from its implementation.

Co-array Fortran also supports more advanced features like array operations and parallel programming constructs, which we’ll explore in later examples.