In Fortran, I can return arrays from a subroutine with three approaches. The first one is via an intent(out)
parameter. The second one is via a function having the array as result
. The third one is to have a function having as result
a pointer to array, which is allocated in the function.
What are the advantages and disadvantages of each approach ?
My practice is to use a function return when the function alters only one variable and makes no other output. If multiple variables are changed or the procedure performs other actions I would place the output variables in the argument list. This is a style choice. It is possible to create memory leaks with pointers, especially with pointers returned as function arguments, so I would avoid this option unless there was a compelling reason in the particular case.
UPDATE: There is no problem with an intent (out) array argument ... no assumptions need be made about the size of the array, as the following example shows:
module example_one
implicit none
contains
subroutine two_arrays ( in_arr, out_arr )
integer, dimension (:), intent (in) :: in_arr
integer, dimension (:), allocatable, intent (out) :: out_arr
integer :: i, len
len = size (in_arr)
allocate ( out_arr (1:len) )
do i=1, len
out_arr (i) = 3 * in_arr (i)
end do
return
end subroutine two_arrays
end module example_one
program test
use example_one
implicit none
integer, dimension (1:5) :: in_arr = [ 1, 2, 4, 5, 10 ]
integer, dimension (:), allocatable :: out_arr
write (*, *) allocated ( out_arr)
call two_arrays ( in_arr, out_arr )
write (*, *) size (out_arr)
write (*, *) out_arr
write (*, *) allocated ( out_arr)
deallocate ( out_arr )
write (*, *) allocated ( out_arr)
stop
end program test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With