LF Fortran 95

RECURSIVE Procedure

Fortran procedures can be RECURSIVE, meaning that they can either directly or indirectly call themselves. The RECURSIVE keyword must be used in the procedure declaration.

Description

A RECURSIVE procedure declaration implies that the procedure may call itself.

Syntax

RECURSIVE SUBROUTINE sub-name([dummy-args])
or
RECURSIVE [type-spec] FUNCTION func-name([dummy-args]) [RESULT(result-name)]
Where:

sub-name is the name of the subroutine.

dummy-args is a comma-separated list of dummy argument names.

type-spec is

INTEGER [kind-selector] REAL [kind-selector] DOUBLE PRECISION COMPLEX [kind-selector] CHARACTER [char-selector] LOGICAL [kind-selector] TYPE (type-name)

kind-selector is ( [KIND=] kind )

char-selector is ( [LEN=] length [, ) KIND=kind])

or (KIND=kind [, LEN=length]) or * char-length [,]

kind is a scalar INTEGER expression that can be evaluated at compile time.

length is a scalar INTEGER expression or *

char-length is a scalar INTEGER literal constant or (*)

func-name is the name of the function.

result-name is the name of the result variable.

Remarks

The RECURSIVE keyword must be present if the procedure directly or indirectly calls itself or a procedure defined by an ENTRY statement in the same subprogram. RECURSIVE must also be present if a procedure defined by an ENTRY statement directly or indirectly calls itself, another procedure defined by an ENTRY statement, or the procedure defined by procedure declaration.

Result

If the recursive procedure is a funcrion, the result is the type and kind of the function declaration or of the result variable.

Example 1

recursive subroutine sub3(i) ! recursive required if the i=i-1 ! subroutine calls itself if(i > 0) call sub3(i) ! directly or indirectly end subroutine

Example 2

! recursive function with result variable recursive function func4(a,b) result(res) real :: res ! result type defined here real :: a,b if (a >= b) then res=a-b ! function returns else if (a < spacing(b)) then res=-b ! function returns else if (a < 0.) then b=func5(-a,b) ! indirect recursion else a=func4(a,-b) ! direct recursion end if end function ! recursive function without result variable recursive function func5(a,b) real :: func5 ! result type defined here real :: a,b if (a < b) then func5=func4(b,a) ! result variable not required else ! if recursive function does func5=func4(a,b) ! not invoke itself directly end if end function

See Also

SUBROUTINE statement

FUNCTION statement