031. Procedures can be recursive#

topic: Procedures

Fortran procedures declared recursive can call themselves.

recursive.f90 | | 0 | Godbolt Compiler Explorer logo | Fortran logo#
! Demonstrate an `elemental recursive` function
module m
   implicit none

contains

   elemental recursive function factorial(n) result(nfac)
      integer, intent(in) :: n
      integer :: nfac

      if (n < 0) then
         nfac = -1
         return
      else if (n < 2) then
         nfac = 1
         return
      else
         nfac = n*factorial(n - 1)
      end if
   end function factorial

end module m

program xfactorial
   use m, only: factorial
   implicit none

   print *, factorial([-1, 0, 1, 4])  ! -1 1 1 24

end program xfactorial
Output1#
          -1           1           1          24

Warning

In GFortran v9 and v10 (and lower versions, presumably), this isn’t allowed, and we get:

Error: ELEMENTAL attribute conflicts with RECURSIVE attribute


1

Compiled using GNU Fortran (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0 with no flags