包装函数中的语句标签
问题描述:
在Fortran中,是否有通过包装函数传递语句标签的方法?包装函数中的语句标签
为了详细说明,我写的包装为open()
,像这样:
program test
contains
subroutine my_open(unit, file, err)
integer, intent(in) :: unit
character(*), intent(in) :: file
integer, intent(in), optional :: err
if (present(err)) then
open(unit, FILE=file, ERR=err)
else
open(unit, FILE=file)
end if
end subroutine my_open
end program test
(当然我的实际过程包含更多的逻辑......)。但gfortran
抱怨
open(unit, FILE=file, ERR=err)
1
Error: Invalid value for ERR specification at (1)
有没有办法做到这一点?
答
对应于err
的标签必须是open
的作用域单元中的标签。所以你想做什么是不可能的。另外,为了回答您的更一般的问题,将标签作为变量传递本身是不可能的(至少,从Fortran 95删除分配的格式和gotos以来)是不可能的。
但是,对于特定情况,可以使用iostat
代替,并将控制权交还给调用子程序。
喜欢的东西(简体):
call my_open(12, file, status)
! Instead of:
! 10 STOP
if (status.ne.0) then
!...
end if
end
subroutine my_open(unit, file, status)
integer, intent(in) :: unit
character(*), intent(in) ::file
integer, intent(out) :: status
open(unit, file=file, iostat=status)
if (iostat.ne.0) return
end subroutine
这无疑是更好的比有什么本质上会是一个goto
从子程序代码的一个非常不同的部分。 [err
在最好的时候并不流行]。此外,这种状态传递可以推广到其他你希望通过标签的情况。