Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning arrays strategy comparison

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 ?

like image 404
Stefano Borini Avatar asked Jan 05 '11 11:01

Stefano Borini


1 Answers

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
like image 65
M. S. B. Avatar answered Oct 02 '22 18:10

M. S. B.