I have noticed that the following piece of code works every time when I compile it using ifort:
real, dimension(:), allocatable :: a
a = [a, 2.0]
print *, a
end program test
In the above, 'a' is undefined and yet it is being used in the statement "a = [a,.2.0]. The above code prints "2.0" correctly. If you compile it using gfortran, then sometimes you will see segfault and sometimes not.
So the question is: Is it safe to use an allocatable array this way when you are only compiling using ifort. I mean does ifort compiler recognizes this code as valid and knows that if 'a' is not allocated already then just allocate a one real size of memory for it?
I find this "feature" very convenient when using Fortran 2008's LHS reallocation. Otherwise, we have to do this:
if (.NOT. allocated(a)) then
a = 2.0
a = [a, 2.0]
The above code works with gfortran as well as ifort but its not very pleasing to me especially inside a loop.
It's not a feature, it's an error in your program. If you compile with pointer checking enabled, you get:
forrtl: severe (408): fort: (8): Attempt to fetch from allocatable variable A when it is not allocated
You cannot and should not depend on the behavior when it is undefined.
Why not allocate the array to zero size initially? Then you don't need to do the test each time.
Mahajan, Bharat wrote:
Thanks for your reply. New to Fortran, didn't even that was an option to allocate it to 0 size. That makes sense.
Don't feel too bad, I have been using Fortran many years and I didn't know allocating to 0 size was possible. :-(
I am pretty sure you are mistaken about no Fortran book mentioning that. The Modern Fortran series by Metcalf, Reid and Cohen does mention it (unless I am terribly mistaken) - it is an example where a language feature helps to formulate algorithms in a clear style. Being able to use zero-length arrays means that you do not have to use a special case for that particular situation.
I suppose it is something one can lightly overlook. Just to be sure, I checked the text of Programming in Fortran 90/95 by J. S. Morgan and J. L. Schonfelder (2000 - very old indeed, but I just had that available). zero-length arrays are not discussed in length it would seem, but the description of the intrinsic functions and subroutines is flooded with such cases ;).