我正在尝试将错误检查合并到我正在编写的纯过程中。我想要这样的东西:
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
但是,纯函数不允许对外部文件有 IO 语句,因此我尝试将单元号传递给函数,例如output_unit = 6
,这是默认输出。 gfortran 仍然认为这是非法的。有没有解决的办法?是否可以使函数成为派生类型(而不是内在类型)real
这里)当出现错误时输出一个字符串?
您不是第一个遇到此问题的人,我很高兴地说标准中的此缺陷将在 Fortran 2015 中得到纠正。如中所述这个文件 http://www.fortran.bcs.org/2013/removing_deficiences.pdf(第 6 页,标题“已批准的标准变更”),“对外观的限制error stop
中的声明pure
应删除程序”.
Fortran 2008 标准包括error stop
声明中介绍了一些新的并行计算功能。它发出错误信号并在可行的情况下尽快停止所有进程。目前,既没有stop
nor error stop
语句允许在pure
过程,因为它们显然不是线程安全的。实际上,在发生内部错误的情况下,这是不必要的限制。
根据您的编译器,您可能需要耐心等待实现。我知道英特尔已实施 https://software.intel.com/en-us/articles/intel-parallel-studio-xe-2016-composer-edition-compilers-fixes-list它在他们的 ifort 编译器中。 (“F2015:解除 PURE/ELEMENTAL 程序中 STOP 和 ERROR STOP 的限制”)
选择
对于替代方法,您可以看看在这个问题上 https://stackoverflow.com/questions/19037789/gfortran-treat-pure-functions-as-normal-functions-for-debugging-purposes,尽管在你的情况下这可能有点棘手,因为你必须改变do concurrent
关键词,不仅仅是pure
.
(正确答案结束)
如果可以选择弄脏手......
与此同时,你可以做一些残酷的事情,比如
pure subroutine internal_error(error_msg)
! Try hard to produce a runtime error, regardless of compiler flags.
! This is useful in pure subprograms where you want to produce an error,
! preferably with a traceback.
!
! Though far from pretty, this solution contains all the ugliness in this
! single subprogram.
!
! TODO: replace with ERROR STOP when supported by compiler
implicit none
character(*), intent(in) :: error_msg
integer, dimension(:), allocatable :: molested
allocate(molested(2))
allocate(molested(2))
molested(3) = molested(4)
molested(1) = -10
molested(2) = sqrt(real(molested(1)))
deallocate(molested)
deallocate(molested)
molested(3) = molested(-10)
end subroutine internal_error
如果有人问,你不是从我这里得到的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)