This is a question crying out for a canonical one, really. In the interest of answering your specific question in the absence (as far as I can tell, but I may write one eventually), I’ll answer.
The argument to
size must not be an unallocated allocatable variable.
For your code
fred is an allocatable variable. If this block of code is executed then on the final line
size has an argument which is an unallocated allocatable variable. In this case if it forms part of a program (program unit) then that program (program unit) is not a standard conforming program (program unit).
This lack of conformance is not a lack of conformance that a Fortran processor is required to detect to be a conforming Fortran processor.
Yes, it would be nice for the processor to detect this, and many will if you choose the appropriate options at compile time. A standard conforming processor will be allowed, in the popular parlance, to start World War III in response to this code. It may also print
3. That is entirely down to the whim of the compiler vendor.
Prompted by the comments, more information.
It’s tempting, perhaps, to expect that the size of a deallocated array is zero. However, a deallocated array and an array with zero elements are quite different things, much as a character of length zero is not the same as an unallocated allocatable character.
In particular, we have idioms like
fred = [fred, append]
which are not valid when
fred is not allocated, but are when it is allocated but of size zero; and it doesn’t need special treatment in this latter case.
I agree with High Performance Mark’s comment that, if the compiler is going to return any value,
0 is a bad choice. Much as the size isn’t well defined any attempt to access
fred(3), say, based on the returned size, is also a bad idea. Again, the compiler is free to give any particular value for this reference.
Finally, if you want to check whether an array is allocated you should use the
allocated intrinsic rather than rely on
0. Of course, in this case it isn’t needed as you can be quite sure that after the
fred is indeed not allocated.
In Fortran 90 it was possible for allocation status to be undefined and then even
allocated wasn’t allowed.
The same ideas apply for things other than arrays and the
size is an inquiry function which requires the array inquired about to be allocated (if an allocatable entity) or pointer associated (if a pointer). Equally, for example, a character with deferred length must be allocated/pointer associated (as applicable) to be an argument to the
len intrinsic inquiry function.
Inquiry functions don’t always require arguments to be allocated/associated. For example, the length of a character of explicit length may be asked about even if the variable is not allocated. One should check the requirements in documentation and not make inquiries which are not allowed.