Rate This Document
Findability
Accuracy
Completeness
Readability

Result Keyword of the Recursive Subroutine

Symptom

The following error is reported during compilation:

test1.F90:13:27:
 
   13 |       func = sqrt(2.0 *func(n-1))
      |                           1
Error: 'func' at (1) is the name of a recursive function and so refers to the result variable. Use an explicit RESULT variable for direct recursion (12.5.2.1)

Cause

According to the specifications, the recursive function must use the result keyword to indicate the return value of the function. If the function name is used as the return value, an error is reported. (Intel Fortran can use the function name as the return value.)

recursive Function func(n)
  real :: func
  integer :: n
  if (n>0) then
      func = sqrt(2.0 *func(n-1))
  else
      func = sqrt(2.0)
  end if
  print *, 'test ', n, func
end

Procedure

Add the result keyword to describe the return value of the function.

recursive Function func(n) result(r)

real :: r
  integer :: n
  if (n>0) then
      r = sqrt(2.0 *func(n-1))
  else
      r = sqrt(2.0)
  end if
  print *, 'test ', n, r
end