Reputation: 441
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?
Upvotes: 0
Views: 619
Reputation: 60113
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)
Upvotes: 3