Reputation: 490
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?
Upvotes: 3
Views: 225
Reputation: 32451
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.
Upvotes: 4