Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use allocatable array as an intent(out) matrix in Fortran?

Consider the following subroutine

subroutine myProc(m,n,flag,X)
Integer, intent(in) :: m,n
logical, intent(in) :: flag
real(8), intent(out), allocatable :: X(:,:)

if (flag) then
  allocate(X(m,n))
  ! some more code here
else 
  allocate(X(m-1,n))
  ! some more code here
end if
end subroutine myProc
!!!!!!!!!!!!!!!!!!!

Also, how do I call this procedure in a program? suppose I write

!... some code before
call myProc(5,6,.TRUE.,X)

Do I need to define X already as a (4,6) real array or pass an allocatable array to the subroutine?

Is doing all of that even possible in Fortran 95?

like image 538
Pitt Prog Avatar asked Nov 18 '22 21:11

Pitt Prog


1 Answers

It is perfectly fine to pass an allocatable dummy argument to subroutine in Fortran 2003 and later. IIRC it was allowed by a TS (technical specification) to Fortran 95 first. All compilers support it today.

The actual argument does not have to be allocated when being passed to an allocatable dummy argument. Here it will actuully be automatically deallocated if it happens to be allocated, because the dummy is intent(out) and allocatable, intent(out) arguments are automatically deallocated when entering the subroutine.

Your code should work fine, but there is one important aspect, the subroutine must have an explicit interface. So it must be placed in a module. Or it must be internal (after contains) or an interface block must be used (ugly).

You can call it as you showed

call myProc(5,6,.TRUE.,X)

and X does not have to be allocated.

like image 138
Vladimir F Героям слава Avatar answered Dec 21 '22 23:12

Vladimir F Героям слава