fortransubroutinefortran95silverfrost-fortran

Defining a subroutine in another subroutine


Is it possible in Fortran to define a subroutine within another subroutine? When I try something like

SUBROUTINE test1(...)
  ! do some stuff
  CALL test2(...)

  SUBROUTINE test2(...)
    ! do some stuff
  END SUBROUTINE test2
END SUBROUTINE test1.

my compiler (Silverfrost) gives me a recursion error.


Solution

  • As HighPerformanceMark comments, it is possible to define an internal procedure in the contains section of another procedure

    SUBROUTINE test1(...)
      ! do some stuff
      CALL test2(...)
    
    CONTAINS
    
      SUBROUTINE test2(...)
        ! do some stuff
      END SUBROUTINE test2
    END SUBROUTINE test1
    

    The internal procedure test2 gets access to all entities defined in the host procedure test1 by host association. It also gets access to all entities that test1 has access to. The rules are similar to the rules of internal procedures in the main program.

    An internal procedure cannot host another internal procedure.

    Procedure pointers to internal procedures are only valid during the execution of the host procedure and are only allowed in Fortran 2008 and later. This is an advanced feature.

    This host association can sometimes be annoying, you must be vigilant to avoid bugs like:

    SUBROUTINE test1(...)
      integer :: i
    
      do i  = 1, n
        CALL test2(...)
      end do
    
    CONTAINS
    
      SUBROUTINE test2(...)
        do i = 1, n
          !i here is the same variable as i in test1!!
        end do
      END SUBROUTINE test2
    END SUBROUTINE test1
    

    There will be features in Fortran 2015 to change the host association behaviour.