7

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...

vaultah
  • 44,105
  • 12
  • 114
  • 143
Alexander Vogt
  • 17,879
  • 13
  • 52
  • 68

2 Answers2

4

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.

High Performance Mark
  • 77,191
  • 7
  • 105
  • 161
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.

ondrejch
  • 29
  • 2
  • It was broken in some gfortran releases. See:https://blog.robertelder.org/gcc-signed-overflow-trapping-ftrapv-doesnt-work/ – ondrejch Aug 20 '19 at 21:11