Subroutines contained in a function

Is it OK to have subroutines contained in a function? I have never seen this kind of style.

There are several reasons why that kind of subprogram is troublesome and inelegant, but it is possible. Here is a contrived example.

program pfib 
   implicit none 
   integer fib 
   Print *,fib (25)
end program

recursive integer function fib (n) ! "recursive" attribute not employed, in reality
   integer, intent (in)::n 
   if (n == 0) then 
      fib = 0
   elseif (n == 1) then 
      fib = 1
   else
      call fibsub (n, fib)
   endif
    
   contains
      subroutine fibsub (n, ifib)
         integer, intent (in)  :: n
         integer, intent (out) :: ifib
         
         integer, save :: sfib(0:30)
         logical :: begin = .true.
         integer i
  
         if(begin)then
            sfib(0:1) = [0,1]
            do i = 2, 30
               sfib(i) = sfib(i-2) + sfib(i-1)
            end do
            begin = .false.
         endif
         ifib = sfib(n)
         return 
     
      end subroutine fibsub 
      
   end function fib 

Try to modify this program to make the function pure, and you may note several of the demerits that I alluded to.

1 Like

Correct me if I am wrong but the only reason the subroutine fibsub (and as a consequence, also the function fib) is not pure is the presence of local variables with save attribute (sfib (explicit) and begin (implicit, as initialized)). And this does not have anything with it being a subroutine. If I understand the OP, the question was whether it is OK for a function to contain a subroutine.

1 Like

Here it is affirmed that you can nest subroutines in order to increase the chances that this part of the code gets inlined.

I use this programming style from time to time, when a function is only called in a particular point of my code (for trivial tasks such as counting the number of lines in an input file or the number of lines in the header of a data file), and I have never encountered any problem at all with that. Maybe, problems arise with more “esoteric” things to be done.

If this is not an advised style, I will try to avoid it the future.