Search code examples
initializationfortrandynamic-allocationderived-types

Fortran pointer to derived types and default initialisation


Fortran 2003 derived types have a nice feature of default initialization.

type TTest
  integer :: a
  integer :: b = 1
  integer, pointer :: p1, p2 => null()
end type TTest

then any declared variable of type (TTest) will have initialized components b and p2 by default.

Consider the following code:

type (TTest), dimension(:), pointer     :: varptr
type (TTest), dimension(:), allocatable :: varalloc
integer, parameter :: ndim = 1000

allocate(  varptr(ndim))
allocate(varalloc(ndim))

Can one be guaranteed that all elements of varptr and varalloc will have initialized b and p2 members after allocation?


Solution

  • Yes, the standard requires that. Whenever you have a variable of that derived type, it will have those components initialized.

    F2008 4.5.4.6.3: If null-init appears for a pointer component, that component in any object of the type has an initial association status of disassociated (1.3) or becomes disassociated as specified in 16.5.2.4.

    F2008 4.5.4.6.6 : If constant-expr appears for a nonpointer component, that component in any object of the type is initially defined (16.6.3) or becomes defined as specified in 16.6.5 with the value determined from constant-expr ...