递归子程序result关键字
问题描述
编译时出现如下报错。
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)
问题原因
规范规定recursive function递归调用的函数需要用result关键字表示函数返回值,用函数名作为返回值会报错(ifort支持函数名做为返回值的写法)。
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
处理步骤
添加result关键字描述函数返回值。
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