Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29229 Discussions

Can MOVE_ALLOC be used with associate-names in an ASSOCIATE construct?

FortranFan
Honored Contributor III
564 Views

Is the run-time behavior shown below with the following code correct?

program p

   implicit none

   type :: t
      character(len=:), allocatable :: s
   end type t

   type(t), allocatable :: foo
   type(t), allocatable :: bar
   type(t), allocatable :: tmp

   foo = t( "foo" )
   bar = t( "bar" )

   asc: associate ( s1 => foo, s2 => bar )

      print *, "before swap: "
      print *, "  foo = ", s1%s
      print *, "  bar = ", s2%s

      !.. swap foo and bar
      call move_alloc(bar, tmp)
      call move_alloc(foo, bar)
      call move_alloc(tmp, foo)

      print *, "after swap: "
      print *, "  foo = ", s1%s
      print *, "  bar = ", s2%s

   end associate asc

   print *, "after associate: "
   print *, "  foo = ", foo%s
   print *, "  bar = ", bar%s

   stop

end program p

Upon execution, the response is:

 before swap:
   foo = foo
   bar = bar
 after swap:
   foo = foo
   bar = bar
 after associate:
   foo = bar
   bar = foo

 

0 Kudos
4 Replies
IanH
Honored Contributor III
564 Views

I recall a restriction on interfering with the allocation status of an object that was the selector in an associate construct.  I can't find that restriction - so perhaps my recollection is being its typical faulty self.

But apart from that - the association is "with the data object" (16.5.1.6) rather than the allocatable variable itself, so what you are seeing is what I would expect.

(In this regard it is similar to having the association be `name => array(index)`, and then after the associate statement change the value of the variable `index`.  The association is with the data object originally designated by array(index), not what that piece of source might subsequently designate in later statements.  In another regard it is also similar to how pointer association works.)

0 Kudos
FortranFan
Honored Contributor III
564 Views

Thanks, great explanation.  It makes perfect sense.  And the pointer analogy is a good one to keep in mind for the associations.

FWIW, gfortran behaves the same as Intel Fortran.

 

0 Kudos
Steven_L_Intel1
Employee
564 Views

The key is that the associate-name does not have the ALLOCATABLE or POINTER attribute, even if the selector does. Section 8.1.3.3 of F2008 tells you which attributes the associate-name picks up.

0 Kudos
FortranFan
Honored Contributor III
564 Views

Thanks Steve.  Section 8.1.3.3 and section 16.5.1.6 for construct association complete the picture.

0 Kudos
Reply