In the following code, I am trying to allocate an empty array of size 0 and add more elements afterward by using automatic reallocation:
integer, allocatable :: a(:)
allocate( a(0) ) ! Line 1
print *, size( a )
print *, "a(:) = ", a
a = [ a, 1 ]
print *, "a(:) = ", a
a = [ a, 2 ]
print *, "a(:) = ", a
!! Error
! a = []
! a = [ integer :: ]
This code gives the expected result (e.g., with gfortran or ifort -assume realloc_lhs)
0
a(:) =
a(:) = 1
a(:) = 1 2
Here I have three questions:
- First of all, is it OK to allocate zero-sized arrays such as
allocate( a( 0 ) )? - If we omit such an explicit allocation, will
a(:)be automatically initialized to a zero-sized array? (Indeed, the code seems to work even if I comment out Line 1.) - Is it no problem to include zero-sized arrays in an array constructor like
a = [a, 1]? (I also tried using an empty array constructor likea = []ora = [integer::], but they did not compile and so seem to be not allowed.)
Edit
If I uncomment a = [] in the above code, gfortran5.3 gives the error message:
Error: Empty array constructor at (1) is not allowed
but if I uncomment only the line a = [ integer :: ], it worked with no problem! Because I initially uncommented both lines at the same time, I misunderstood that the both ways are illegal, but actually the latter seems OK (please see @francescalus answer).
ctrl+F5under release mode within ifort+vs2013, but the last two lines of results:a(:) = 1 a(:) = 1 2didn't show up. Did you compile your code under some special mode? (I don't quite get the purpose of option-assumeandrealloc_lhs)a = [ a, 1 ]anda = [ a, 2 ]perform so-called "automatic reallocation" (a recent feature in Fortran), which does allocate() implicitly on the array of the left-hand side when the array size is different from the right-hand side. (For example, in the case of a = [ a, 1 ], the right-hand side is a 1-element array and we try to assign it toa. Because the originalahas no element (size 0), we need to deallocate()/allocate()aif we use Fortran90, but with this new syntax it is re-allocateed automatically to correct size.-assume realloc_lhs(or-standard-semantics) explicitly. AFAIK, we need this option up to Intel Fortran 16. But from ifort-2017, this option becomes the default, so the above code works without any option (probably). --- Sorry for my poor explanations, and if you need more information, please consider posting a new Question (I guess you will get more solid info :)-assume realloc_lhsin the case of ifort because I used ifort-14 at that time. (On the other hand, I did not attach any option for gfortran.)