代码之家  ›  专栏  ›  技术社区  ›  lbjx

如何从子程序返回值

  •  1
  • lbjx  · 技术社区  · 11 年前

    我不想使用全球价值——这对一个大项目来说是危险的。代码是这样的

    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 回复  |  直到 11 年前
        1
  •  2
  •   High Performance Mark    11 年前

    这样地

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

    call test(3,myflag)
    

    将myflag设置为 .true.

    笔记

    • 子程序通过其参数列表返回值;
    • 使用 intent 子句,告诉编译器子程序可以对其参数做什么;
    • 我的例子很简单,你可能会想根据自己的需要进行调整。
        2
  •  2
  •   cup    11 年前

    你也可以用函数来实现。假设偶数为真

    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