递归函数中的运行时检查失败

时间:2014-06-30 17:11:37

标签: recursion fortran runtime intel-fortran

当我使用运行时检查编译程序时,我收到以下错误(我不明白为什么):

ifort -check all test.f90 -o test
./test
forrtl: severe (193): Run-Time Check Failure. The variable 'my_sum$2$_2' is being used without being defined
Image        PC                     Routine           Line           Source
sum          0000000000403098       Unknown              Unknown     Unknown 
sum          0000000000403098       Unknown              Unknown     Unknown 
sum          0000000000403098       Unknown              Unknown     Unknown 
sum          0000000000403098       Unknown              Unknown     Unknown 
.
.
.
sum          0000000000403098       Unknown              Unknown     Unknown 
sum          0000000000402EAF       Unknown              Unknown     Unknown 
sum          0000000000402DE6       Unknown              Unknown     Unknown 
libc.so.6    00007F7FEB268BE5       Unknown              Unknown     Unknown 
sum          0000000000402CD9       Unknown              Unknown     Unknown 

代码是:

program test

   implicit none
   real(8) :: x

   x=my_sum(lambda_i,0,200)
   print*,x

contains

   function lambda_i(n) result(i)
      real(8) :: i
      integer,intent(in) :: n
      i=dble(n)
   end function

   recursive function my_sum(f,i,n) result(s)
      implicit none
      real(8) :: s
      integer, intent(in) :: i,n
      interface
         function f(n)
         implicit none
         real(8) :: f
         integer,intent(in) :: n
         end function
      end interface

      if ( n .ge. 0 ) s=f(n)+my_sum(f,i,n-1)
   end function

end program

有人有想法吗?没有检查,程序运行正常,除非我达到递归限制。

1 个答案:

答案 0 :(得分:4)

我认为问题是

if ( n .ge. 0 ) s=f(n)+my_sum(f,i,n-1)

到达n .lt. 0后,未定义返回值s,函数返回未定义的变量(就像ifort抱怨一样)。由于这是递归的最后一步,并且所有其他结果都依赖于此,因此总结果是未定义的。

使用

可以避免这种情况
if ( n .ge. 0 ) then 
  s=f(n)+my_sum(f,i,n-1)
else
  s=0._8
endif