Automatic array allocation upon assignment in Fortran

The validity of code like

integer, allocatable :: array(:)
array = (/1,2,3/)

depends on the standard of Fortran used to interpret it.

Fortran 2003 introduced the concept of automatic allocation on intrinsic assignment. Before Fortran 2003 the array on the left-hand side of such an assignment statement must be allocated, and of the same shape as the array on the right-hand side.

From Fortran 2003 only the rank needs match. If there is a shape mismatch, the array would be first deallocated and then reallocated to the correct shape. If not allocated initially, it would be allocated.

So, the program above isn’t valid Fortran 90, but is valid Fortran 2003.

The difference in the real-world code, then, is from what language syntax the compilers support.

For gfortran, Fortran 2003’s assignment to an allocatable array was introduced in 4.6, 2011-01-28.

As also commented, the command line option -fno-realloc-lhs1 disables this automatic (re-)allocation, making the compiler not Fortran 2003+ compliant.

1 Other compilers have similar behaviour: adding a required check for whether reallocation is necessary is a performance hit which is redundant in Fortran 90 compliant code and may be a feature not used by many even in modern code. For Intel’s compiler, for example, in some versions which do support F2003 the default is to ignore this.

One can always suppress the (re-)allocation checks/actions of an array in modern code by using an array section

array(:) = (/1,2,3/)

In this case, array (if allocatable) must be allocated, of rank 1 and of size 3 for the assignment statement to be valid. This is as would be under a Fortran 90 interpretation of the assignment with the whole array array=(/1,2,3/).

The reason for this is that with the array section of this footnote, the left-hand side is not allocatable, even though the array itself is.

Leave a Comment