包装函数中的语句标签 [英] Statement labels in wrapper functions
问题描述
的包装器, open()
,如下所示: 程序测试
包含
子例程my_open(unit,file,err)
整数,意图(in)::单元
字符(*),intent(in)::文件
整数, :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(单位,FILE = file,ERR = err)
1
错误:在(1)
有没有办法做到这一点?
标签对应于 err
必须是打开
的范围单元中的标签。所以你想做什么是不可能的。另外,为了回答您的更一般的问题,将标签作为变量传递本身是不可能的(至少,自从Fortran95删除了分配的格式和gotos以来)。然而,
然而, ,对于具体的情况,可以使用 iostat
来代替,并且可以将控制权传递给调用子程序。
Something像(简体):
call my_open(12,file,status)
!而不是:
! 10 STOP
if(status.ne.0)then
!...
end if
end
子程序my_open(unit ,文件,状态)
整数,意图(in)::单元
字符(*),意图(in)::文件
整数,意图(输出)::状态
open(unit,file = file,iostat = status)
if(iostat.ne.0)返回
结束子程序
这可以说比从本质上讲是一个 goto
的代码的一个非常不同的部分要好得多子程序。 [ err
在最好的时候并不流行。]此外,这种状态传递可以推广到其他您需要传递标签的情况。
In Fortran, is there a way to pass a statement label through a wrapper function?
To elaborate, I am writing a wrapper for open()
, like so:
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
(of course my actual procedure contains more logic …). But gfortran
complains
open(unit, FILE=file, ERR=err)
1
Error: Invalid value for ERR specification at (1)
Is there a way to do this?
The label corresponding to err
has to be a label in the scoping unit of the open
. So what you want to do isn't possible. Also, to answer your more general question, passing labels as variable isn't possible in itself (at least, since Fortran 95 which deleted assigned formats and gotos).
However, for the specific case, using iostat
instead, and passing control back to the calling subprogram is possible.
Something like (simplified):
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
This is arguably much better than having what would essentially be a goto
to a very different part of the code from the subroutine. [err
isn't popular at the best of times.] Further, this status-passing can be generalized to other cases where you would want to pass labels.
这篇关于包装函数中的语句标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!