Multiple Return Values in Fortran

Fortran has built-in support for multiple return values through the use of derived types or arrays. This feature can be used to return both result and error values from a function.

module multiple_return_values
  implicit none

  ! Define a derived type to hold multiple return values
  type :: result_pair
    integer :: a
    integer :: b
  end type result_pair

contains

  ! This function returns a derived type containing 2 integers
  function vals() result(res)
    type(result_pair) :: res
    res%a = 3
    res%b = 7
  end function vals

  subroutine main()
    type(result_pair) :: result
    integer :: c

    ! Here we use the derived type to get multiple return values
    result = vals()
    print *, result%a
    print *, result%b

    ! If you only want a subset of the returned values,
    ! you can simply ignore the unwanted values
    result = vals()
    c = result%b
    print *, c
  end subroutine main

end module multiple_return_values

program run_example
  use multiple_return_values
  call main()
end program run_example

To run the program, save it as multiple_return_values.f90 and compile it using a Fortran compiler:

$ gfortran multiple_return_values.f90 -o multiple_return_values
$ ./multiple_return_values
           3
           7
           7

In Fortran, we don’t have a direct equivalent to the blank identifier _ used in some other languages. However, we can simply ignore unwanted values by not assigning them to variables.

Fortran doesn’t have built-in support for multiple return values in the same way as some modern languages, but we can achieve similar functionality using derived types or arrays. This example demonstrates how to use a derived type to return multiple values from a function.

The next example might cover more advanced features of Fortran subroutines and functions.