0

I am new to fortran, and am wondering whether it is possible to write a function or subroutine with dynamic input? For example, if I want a function/subroutine :

function/subroutine a (inputs)

  integer, dimension(:), allocatable :: b
  integer :: i,j

  i = number of inputs
  allocate(b(i))

  do j=1,i
    b(i)=input(i)
  end do

end function a

So the number of inputs can be different every time I call the function/subroutine. Is it possible?

user3716774
  • 431
  • 3
  • 11
  • 1
    Fortran uses optional arguments, and you can check if such argument is present or not with the function present. but to my knowledge, you can not just query the number of arguments, you have to check each individually. And all must be declare in the signature of the function. – innoSPG Jul 11 '15 at 01:18
  • If you are allocating in the function and not returning the allocated array, remember to deallocate before you exit otherwise you will end up with a massive memory leak. – cup Jul 11 '15 at 09:31
  • 2
    @cup As of Fortran 95 allocatable arrays are deallocated automatically. I never deallocate them. As of Fortran 2003 that also holds for all allocatable entities. – Vladimir F Героям слава Jul 11 '15 at 09:36

1 Answers1

3

When all the arguments are of the same type, you can pass them in an array:

subroutine a(inputs)
    integer :: inputs(:)
    integer,  allocatable :: b(:)
    integer :: i,j

    i = size(inputs)
    allocate(b(i))

    do j=1,i
      b(i)=input(i)
    end do

If they are of different types you can use optional dummy arguments. You must check every argument if it is present before accessing it.

subroutine a(in1, in2, in3)
    integer :: in1
    real :: in2
    character :: in3

    if (present(in1)) process in1
    if (present(in2)) process in2
    if (present(in3)) process in3

You can also use generics, where you manually specify all possible combinations and the compiler then selects the right specific procedure to call. See your favorite textbook or tutorial for more

module m

  interface a
    module procedure a1
    module procedure a1
    module procedure a1
  end interface

contains

   subroutine a1(in1)
     do something with in1
   end subroutine

   subroutine a2(in1, in2)
     do something with in1 and in2
   end subroutine

   subroutine a2(in1, in2, in3)
     do something with in1, in2 and i3
   end subroutine

end module

...
use m
call a(x, y)
  • when I am using the first subroutine, it says explicit interface required. if I contain the subroutine in the main program, it works. Why does it happen? – user3716774 Jul 13 '15 at 20:02
  • Use modules http://stackoverflow.com/questions/16486822/fortran-explicit-interface http://stackoverflow.com/questions/11953087/proper-use-of-modules-in-fortran http://stackoverflow.com/questions/8412834/correct-use-of-modules-subroutines-and-functions-in-fortran Read carefully, it is not short, but very important. – Vladimir F Героям слава Jul 13 '15 at 20:44