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
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)
."