fortranfortran2003fortran2008

Allocate multiple variables at once with SOURCE=


I am now trying to update my old Fortran code that includes the lines like (*)

allocate( a(2), b(2) )
a(:) = 0.0
b(:) = 0.0

Initially, I changed them to

allocate( a(2), source=0.0 )
allocate( b(2), source=0.0 )

but this is clearly not much simple. So I tried to combine them so that

allocate( a(2), b(2), source=0.0 )    !! (1)

I didn't expect it to work, but it actually worked for gfortran >=4.8 and Sun fortran 8.7 (while not for ifort-14). So I went through the ALLOCATE section of the F2003 and F2008 documents, and it seems that the restriction has been removed in F2008 that "If SOURCE= appears, allocation-list shall contain only one allocate-object". Does this mean that the above line 1 is no problem in F2008, and that the different behavior is simply due to different degree of F2008 support?

(*) In actual codes, I was trying to allocate several array components of a derived type, allocate( conf% crd(3,N), conf% vel(3,N), conf% frc(3,N), blah, blah,... ) while assigning zero to each of them. So I was wondering if it is possible to simplify those lines somewhat.


Solution

  • At the high level, yes, the restriction in Fortran 2003 that there is only one object in a sourced allocation is removed in Fortran 2008.

    Now, on to other matters. First, you don't show the declarations of a and b. In a sourced allocation the objects to be allocated must be type compatible with the source. The simple case

    real, allocatable, dimension(:) :: a, b
    allocate( a(2), b(2) )
    a(:) = 0.0
    b(:) = 0.0
    

    has the same Fortran 2008 effect as

    real, allocatable, dimension(:) :: a, b
    allocate( a(2), b(2), source=0.0 )
    

    But what about

    double precision, allocatable, dimension(:) :: a, b
    allocate( a(2), b(2), source=0.0 )
    

    ?

    And the second point from before is: Fortran 2008 is a relatively new thing. I don't trust all compilers to correctly implement the rules with multiple objects in a sourced allocation.