如何从子例程返回值

时间:2013-11-01 15:23:51

标签: return-value fortran90 subroutine

我不想使用全球价值,这对大型项目来说是危险的。代码就像这样

subroutine has_key(id)
  if (true) then 
     return 1
  else
     return 0
  end if
end subroutine

subroutine main
   if(has_key(id))
      write(*,*) 'it works!'
end subroutine

如何使用子程序执行此类操作。我在考虑返回一个标志,但我可能会使用全局值。有人有想法吗?

2 个答案:

答案 0 :(得分:2)

喜欢这个

subroutine test(input, flag)
   integer, intent(in) :: input
   logical, intent(out) :: flag
   flag = input>=0
end subroutine

call test(3,myflag)

会将myflag设置为.true.

注意

  • 子例程通过参数列表返回值;
  • 使用intent子句告诉编译器子程序可以对其参数做什么;
  • 我的例子非常简单,您可能希望根据自己的需要进行调整。

答案 1 :(得分:2)

你也可以用一个功能来做。假设它为偶数

返回true
logical function has_key(id)
   integer, intent(in):: id
   has_key = mod(id,2) .eq. 0
end function has_key

program main
   do ii = 1, 4
      if(has_key(ii))
         print *, ii, ' has key'
      else
         print *, ii, ' no key'
      end if
   end do
end program
相关问题