(Class-) array finalization and initialization question

Salvatore Filippone filippone.salvatore@gmail.com
Wed Feb 18 15:05:00 GMT 2015


>Note the intent(out) here, which is the second crucial point and in combination
>with the call to init() in the main program:
>
 > type(t1), allocatable :: x(:,:)
  >allocate(t1 :: x(5,5))
  >x%i = 1
  >call init(x(::2, ::3))
>
>one gets the remarkable result, that now x%i is -13 for the entries selected by
>the strides. My question now is: why are those values -13 and not 42 as I would
>expect from the default initializer? The array elements selected by the strides
>have been undefined when calling init() as of F2008 5.3.10 Â3 (first sentence)
>hence calling the finalizer. But from that same sentence I would expect the
>default-initializer to be set for the values instead.

Because the default inizializer is called when you invoke ALLOCATE,
whereas the finalizer is invoked at the time you enter the INIT
routine since it has an INTENT(OUT) dummy argument.
Since within INIT you do not touch the X argument anymore, the output
is consistent with the rules.

Saying it again, the default initializer is only invoked when you
create a new variable instance by an ALLOCATION, or (as in the
attached example) by using an automatic array of the correct type
module type_mod
type t1
    integer :: i = 42
  contains
    final :: fin
  end type t1
contains
  elemental subroutine fin(x)
    type(t1), intent(inout) :: x
    x%i = -13 * x%i
  end subroutine fin
end module type_mod

module init_mod
  use type_mod
contains
  subroutine init(x)
    type(t1), intent(out) :: x(:,:)
    type(t1) :: a(size(x,1),size(x,2))
    x = a
  end subroutine init
end module init_mod

program tryfin
  use init_mod


  type(t1), allocatable :: x(:,:)
  allocate(t1 :: x(5,5))
  x%i = 1
  call init(x(::2, ::3))

  write(*,*) x%i
end program tryfin


which produces
[sfilippo@localhost PSBLAS_V3]$ ./tryfin
          42           1          42           1          42
1           1           1           1           1           1
 1           1           1           1          42           1
 42           1          42           1           1           1
   1           1


because the initializer is called when you instantiate the local variable A.

Salvatore



More information about the Fortran mailing list