next up previous contents
Next: Recursive Subroutines Up: More on Procedures Previous: Optional Arguments   Contents

Recursive Functions

Recursion = procedures call themselves (either directly or indirectly). This is a powerful, but dangerous feature: if used incorrectly, the efficiency, and sometimes the meaning of the algorithm may suffer.

The declaration of a recursive function may be

integer recursive function fact(n) result(n_fact)
The RESULT keyword specifies a variable where the result of the function is stored; this is necessary since the name of the function cannot be used to return the result for efficient implementation reasons. The value of dummy argument N_fact will be returned to the caller under the name fact; clearly, the type of the function (fact) must coincide with the type of the returned variable (N_fact); it is enough to declare only one of them. Above, we declared fact to be INTEGER, and this automatically declares N_fact INTEGER. Alternatively, we can declare N_fact, and this will automatically extend to fact (see example below).

In our previous lectures on functions we learned that, by default, the name of the return variable coincides with the name of the function. With any function (recursive or not), it is possible to rename the return variable using the statement RESULT(ret_var) in the function header.

The full example of the declaration and use of factorial function:

recursive function fact(n) result(n_fact) 
 integer, intent(in) :: n 
 integer:: n_fact 
 if (n > 0) then 
   n_fact = n*fact(n-1)  
 else 
   n_fact = 1  
 end if 
end function fact

The function repeatedly calls itself, with decreased n, until the argument is 0, when the recursion begins to unwind.


next up previous contents
Next: Recursive Subroutines Up: More on Procedures Previous: Optional Arguments   Contents
Adrian Sandu 2001-08-26