fortrangfortran

Integer division by zero in Fortran


Consider the following example:

integer::i
i=0
print*,0/i
print*,1/i
end

Newer compilers (gfortran 13.1.0 and ifx 2024.1.2) generate an executable that prints two zeros, while an older compiler that I found (gfortran 7.4.0) generates an executable that prints only one zero and interrupts execution with "SIGFPE: Floating-point exception - erroneous arithmetic operation", although it is not a floating-point operation.

According to the Fortran Interpretation Document (10.1.5.2.2 Integer division): "The result of [integer division] is the integer closest to the mathematical quotient and between zero and the mathematical quotient inclusively." I didn't find any information about handling integer division by zero.

What should be the correct result of executing this code according to the standard? Or is this behavior undefined?

(A similar question was asked in this post about an older version of Fortran. I'm interested in Fortran 2003 or later. This behavior might have changed considering the difference between the compilers mentioned above. Also, there are no replies in this post that answer the question from the author: "How does F77 handle division by zero for INT division?" Additionally, my question is related to the Fortran standard.)


Solution

  • Your code is invalid Fortran, so a Fortran processor can do anything it wants. This includes doing what you expect or deleting your filesystems.

    Fortran 2023, page 163

    10.1.5.2.4 Evaluation of numeric intrinsic operations

    The execution of any numeric operation whose result is not defined by the arithmetic used by the processor is prohibited.

    The prohibition is not a number constraint. A Fortran processor need not catch or issue an error or warning. The prohibition is on the programmer.