纯Fortran程序中的I/O.

Sam*_*Tan 7 io error-handling fortran gfortran fortran95

我正在尝试将错误检查纳入我正在编写的纯过程中.我想要像:

pure real function func1(output_unit,a)
    implicit none
    integer :: a, output_unit

    if (a < 0) then
        write(output_unit,*) 'Error in function func1: argument must be a nonnegative integer. It is ', a
    else
    func1 = a/3

    endif
    return
end function func1
Run Code Online (Sandbox Code Playgroud)

但是,不允许纯函数将IO语句赋予外部文件,因此我尝试将单元号传递给函数,例如output_unit = 6,这是默认输出.gfortran仍然认为这是非法的.有没有解决的办法?是否有可能使函数成为派生类型(而不是real此处的内部类型),在出现错误时输出字符串?

Sam*_*Tan -1

我自己找到了答案,详细信息在这里。它使用了被认为“过时”的东西,但仍然有效;这称为交替返回。将过程编写为子例程,因为它不适用于函数。

pure real subroutine procA(arg1)
    implicit none
    integer :: arg1

    if (arg < 0) then
        return 1 ! exit the function and go to the first label supplied
                 ! when function was called. Also return 2, 3 etc.
    else
        procA = ... ! whatever it should do under normal circumstances
    endif
endsubroutine procA

.... 

! later on, procedure is called
num = procA(a, *220)

220 write(6,*) 'Error with func1: you've probably supplied a negative argument'
Run Code Online (Sandbox Code Playgroud)

eriktous 所建议的可能会更好——让过程返回一个状态,可能是一个逻辑值或一个整数,并让程序在每次调用该过程后检查这个值。如果一切顺利,继续。否则,打印相关错误信息。

欢迎评论。

  • 啊!请不要使用这个。它被标记为过时是有原因的。当前标准建议将以下内容作为替代方案(与我的建议基本相同):“使用返回时在 SELECT CASE 构造中使用的返回代码可以实现相同的效果。” (3认同)