How to declare an array variable and its size mid-routine in Fortran

arrays, fortran

Solution

Your question isn't about initializing an array, which involves setting its values.

However, there is a way to do what you want. You even have a choice, depending on how general it's to be.

I'm assuming that the `element_count` means to have a `some_array(i)` in that loop.

You can make `new_array` `allocatable`:

subroutine example(some_array)
  real some_array(50)
  real, allocatable :: new_array(:)

  allocate(new_array(COUNT(some_array.gt.0)))
end subroutine

Or have it as an automatic object:

subroutine example(some_array)
  real some_array(50)
  real new_array(COUNT(some_array.gt.0))
end subroutine

This latter works only when your condition is "simple". Further, automatic objects cannot be used in the scope of modules or main programs. The `allocatable` case is much more general, such as when you want to use the full loop rather than the `count` intrinsic, or want the variable not as a procedure local variable.

In both of these cases you meet the requirement of having all the declarations before executable statements.

Since Fortran 2008 the `block` construct allows automatic objects even after executable statements and in the main program:

program example

  implicit none

  real some_array(50)
  some_array = ...

  block
    real new_array(COUNT(some_array.gt.0))
  end block

end program example

Problem

I would like to create an array with a dimension based on the number of elements meeting a certain condition in another array. This would require that I initialize an array mid-routine, which Fortran won't let me do. Is there a way around that? Example routine: ``` subroutine example(some_array) real some_array(50) ! passed array of known dimension element_count = 0 do i=1,50 if (some_array.gt.0) then element_count = element_count+1 endif enddo real new_array(element_count) ! new array with length based on conditional statement endsubroutine example ```

Original source