1

In Fortran, if I use an allocatable array that is not allocated in an array assignment, I expect that there will appear some runtime errors. But it turns out that the allocatable array got allocated during the assignment. This seems to be a dangerous design. Could someone explain the reason for this design? An example code is as follows:

module yj_mod
 real,dimension(:,:),allocatable :: den_i_right
end module yj_mod

program main
  call p()
end program main

subroutine p()
  use yj_mod,only : den_i_right
  implicit none
  real :: a(3,4)
  a=3.0
  den_i_right=a
write(*,*) size(den_i_right,1), size(den_i_right,2)
end subroutine p

I compiled the above code with gfortran. Running the code indicates den_i_right becomes an array of the same shape as a

Youjun Hu
  • 991
  • 6
  • 18
  • After I asked this question, I searched and found out that this question had indeed been asked before and already has an answer. But my question seems to be more concise than that question, which involves many lines of codes. – Youjun Hu Dec 21 '18 at 22:56
  • 1
    _"This seems to me a dangerous design."_ Actually, it is a design decision that brings Fortran closer to other, more recent, languages. And it can be, indeed, dangerous. Ya gotta love it! – Rodrigo Rodrigues Dec 22 '18 at 00:28

1 Answers1

2

It is informally called (..... wait for it .....) (re-)allocation on assignment. The specific language from the Fortran 2003 standard using variable=expr

"If variable is an allocated allocatable variable, it is deallocated if expr is an array of different shape or any of the corresponding length type parameter values of variable and expr differ. If variable is or becomes an unallocated allocatable variable, then it is allocated with each deferred type parameter equal to the corresponding type parameters of expr, with the shape of expr, and with each lower bound equal to the corresponding element of LBOUND(expr)."

Steve
  • 301
  • 1
  • 3