Can I guarantee `allocatable` variables to start out not allocated?

In C#, if you want to indicate that an integer may or may not be there, you can mark it nullable, like this:

int? x = null;

This is useful when you don’t have a value that’s “invalid”, like 0, that lets you know the value isn’t there. In Fortran, marking a scalar allocatable achieves a similar result

integer, allocatable :: x

I know you can’t rely on local variables to have any value when declared. Is the same true for allocatable variables? My actual use-case involves an array of custom types:

type :: my_type
  real, allocatable :: ent
  real, allocatable :: lvg
end type

subroutine s(n)
  integer, intent(in) :: n
  type(my_type), allocatable :: arr(:)

  allocate(arr(n))
  ! ...
end subroutine

Can I count on all elements of arr to have unallocated ent and lvg variables?

Yes, the language states that all allocatable variables and components have an initial status of unallocated.

2 Likes

You may find gfortran’s behavior surprising in this regard. You can bypass the surprise (allocated status upon second call) by explicitly deallocating the local allocatable objects before exiting the procedure.

Which behavior are you referring to?

The following

implicit none

type :: my_type
  real, allocatable :: ent
  real, allocatable :: lvg
end type

call s(5)
call s(6)

contains
    subroutine s(n)
      integer, intent(in) :: n
      integer :: i
      type(my_type), allocatable :: arr(:)

      allocate (arr(n))
      print*,'size(arr)=', size(arr)
      print*,(allocated(arr(i)%ent), allocated(arr(i)%lvg), i = 1, n)
      ! ...
    end subroutine
end

Seems to work just fine:

$ gfortran gfortran-alloc.f90 && ./a.out
 size(arr)=           5
 F F F F F F F F F F
 size(arr)=           6
 F F F F F F F F F F F F

This is a relevant discussion:

Maybe the new gfortran has improved.

1 Like

I’ve come across the following question on StackOverflow, which may be related to the unexpected behavior of allocatable by Gfortran (linked in the above post, which is still reproducible with Gfortran-14 on Godbolt). Indeed, this may be a bug of the option -fmax-stack-var-size itself, though not sure about details.

EDIT: Here is the man page for this option.

This option currently only affects local arrays declared with constant bounds, and may not apply to all character variables.

Also a previous thread on this option (not related to the above issue):

1 Like