Catch integer exceptions in Fortran

▼魔方 西西 提交于 2019-12-19 22:25:11

问题


Is there a way to catch integer exceptions with gfortran or ifort like there is for catching floating point exceptions?

Consider this simple program to calculate the factorial:

program factorial
  use, intrinsic :: iso_fortran_env 

  implicit none
  integer(8)          :: fac
  real(REAL64)        :: facR
  integer,parameter   :: maxOrder = 30
  integer             :: i

  fac = 1 ; facR = 1.e0_REAL64
  do i=2,maxOrder
    fac=fac*i ; facR=facR*real(i,REAL64)
    write(*,*) i, fac, facR
  enddo ! i

end program

At some point there will be an overflow - for integer(8) as shown here, it will occur at around 21. But without the calculation using floats as a reference I couldn't tell for sure...


回答1:


There is nothing in the Fortran standard that deals with integer overflow. As it stands you can't even rely on integers wrapping round when a computation exceeds the maximum value representable in the chosen kind. So, while a test such as

huge(2_8)+1 < 0_8

is likely to work with most current compilers (at least the ones I have used recently) it's not guaranteed.

I am sure that neither Intel Fortran nor gfortran provide compiler-generated run-time checks for integer overflow either. I'm not sure about other compilers but I'll be (pleasantly) surprised to learn that any of them do.

I think, therefore, that you have to proceed with your current approach.




回答2:


gfortran will catch integer overflow with -ftrapv flag, see man gcc:

-ftrapv This option generates traps for signed overflow on addition, subtraction, multiplication operations.

ifort does not seem to have that capability.



来源:https://stackoverflow.com/questions/18881865/catch-integer-exceptions-in-fortran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!