Variadic Functions in Fortran

Variadic functions can be called with any number of trailing arguments. For example, fmt.Println is a common variadic function.

Here’s a function that will take an arbitrary number of ints as arguments.

program variadic_example
  implicit none
  integer :: nums(0:10), i
  
  call sum((/1, 2/))
  call sum((/1, 2, 3/))
  
  nums = (/1, 2, 3, 4/)
  call sum(nums(1:4))
contains
  
  subroutine sum(nums)
    integer, intent(in) :: nums(:)
    integer :: i, total
    
    write(*,'(A)', advance='no') '(', advance='no'
    do i = 1, size(nums)
      write(*,'(I0)', advance='no'), nums(i)
      if (i < size(nums)) then
        write(*,'(A)', advance='no') ', '
      end if
    end do
    write(*,'(A)', advance='no') ') ', advance='no'

    total = 0
    do i = 1, size(nums)
      total = total + nums(i)
    end do
    write(*,*) total
  end subroutine sum

end program variadic_example

Within the subroutine, the type of nums is equivalent to integer array. We can call size(nums), iterate over it with a loop, etc.

Variadic functions can be called in the usual way with individual arguments.

call sum((/1, 2/))
call sum((/1, 2, 3/))

If you already have multiple arguments in an array, apply them to a variadic function using array slicing like this.

nums = (/1, 2, 3, 4/)
call sum(nums(1:4))
$ gfortran variadic_example.f90 -o variadic_example
$ ./variadic_example
(1, 2) 3
(1, 2, 3) 6
(1, 2, 3, 4) 10

Another key aspect of functions in Fortran is their ability to handle array arguments and perform operations over them efficiently.