Integer division, MOD and overflow
Integer arithmetic in Fortran is exact, truncating and finite. The first two properties are what a reader wants; the third is where the bugs are. This lesson covers division that truncates toward zero, the two remainder functions that disagree about negative numbers, and the two ways an integer can leave its range: the one the compiler reports and the one it does not.
Truncating division
An integer divided by an integer is an integer, and the result is the quotient truncated toward zero. That makes -7 / 2 equal to -3 and not to -4, which is the first difference from a floor division, and it makes 7 / 2 equal to 3.
The file divmod.f90:
program divmod
implicit none
integer :: a, b
a = 7
b = 2
print *, "7 / 2 :", a / b
a = -7
print *, "-7 / 2 :", a / b
print *, "mod(-7, 2) :", mod(a, b)
print *, "modulo(-7, 2):", modulo(a, b)
b = -2
print *, "mod(7, -2) :", mod(7, b)
print *, "modulo(7, -2):", modulo(7, b)
end program divmod
gfortran -Wall -Wextra -std=f2018 divmod.f90 -o divmod
./divmod
7 / 2 : 3
-7 / 2 : -3
mod(-7, 2) : -1
modulo(-7, 2): 1
mod(7, -2) : 1
modulo(7, -2): -1
The truncation has a cost in a program that walks a grid: a cell index computed by division is wrong by one for every negative coordinate, and the error is a half cell on one side of zero only. Use floor on the real value, or offset the coordinates, when negative values are possible.
MOD and MODULO
Two intrinsics answer the remainder question and they differ exactly when the operands have different signs:
- mod(a, p) has the sign of a, the dividend. It satisfies a = int(a / p) * p + mod(a, p), which is the truncating division above.
- modulo(a, p) has the sign of p, the divisor. It is the result a mathematician expects: modulo(-7, 2) is 1 because -7 is one more than a multiple of 2 going down.
A periodic index or an angle wrap wants modulo, because its result stays in the range 0 to p - 1 for a positive p, negative arguments included. A program that splits a value into a quotient and a remainder and expects q * p + r to give the value back wants mod.
Overflow the compiler catches
When both operands are constants, the compiler computes the result itself and reports an overflow. That is the good case: the build stops before a program exists that would compute a wrong number.
The file overflow.f90:
program overflow
use iso_fortran_env, only: int32
implicit none
print *, "huge(0_int32) + 1:", huge(0_int32) + 1_int32
end program overflow
gfortran -Wall -Wextra -std=f2018 overflow.f90 -o overflow
overflow.f90:5:32:
5 | print *, "huge(0_int32) + 1:", huge(0_int32) + 1_int32
| 1
Error: Arithmetic overflow at (1)
huge(0_int32) is the largest value of the 4-byte integer, 2147483647, and one more does not fit in the type of the expression. The compiler knows both operands, so it refuses.
A power is checked the same way. 2_int32 ** 31 is 2147483648 as a mathematical value and out of range for the type, so a program that prints it does not build.
The file pow.f90:
program pow
use iso_fortran_env, only: int32
implicit none
print *, "2_int32 ** 31:", 2_int32 ** 31
end program pow
gfortran -Wall -Wextra -std=f2018 pow.f90 -o pow
pow.f90:5:36:
5 | print *, "2_int32 ** 31:", 2_int32 ** 31
| 1
Error: Result of exponentiation at (1) exceeds the range of INTEGER(4)
Overflow that wraps
The same sum with a variable in it compiles, runs and produces a value in the wrong range. Integer arithmetic in Fortran wraps: the result is the low bits of the true value, reinterpreted as a signed integer.
The file wrap.f90:
program wrap
use iso_fortran_env, only: int32
implicit none
integer(int32) :: big, wrapped
big = huge(0_int32)
wrapped = big + 1_int32
print *, "big :", big
print *, "big + 1 :", wrapped
print *, "smallest:", -big - 1_int32
end program wrap
gfortran -Wall -Wextra -std=f2018 wrap.f90 -o wrap
./wrap
big : 2147483647
big + 1 : -2147483648
smallest: -2147483648
Two lines make the same point from both ends: one more than the largest value is the smallest value. Nothing in the build said anything, and a program that sums a million counts can pass through this boundary without a warning.
A constant division warns about the truncation it performs, which is the one place gfortran reports the arithmetic a reader might not have intended:
The file trunc.f90:
program trunc
implicit none
print *, "7 / 2 :", 7 / 2
print *, "7.0 / 2:", 7.0 / 2
end program trunc
gfortran -Wall -Wextra -std=f2018 trunc.f90 -o trunc
trunc.f90:4:23:
4 | print *, "7 / 2 :", 7 / 2
| 1
Warning: Integer division truncated to constant '3' at (1) [-Winteger-division]
The build succeeds after the warning, and the run prints the two lines:
./trunc
7 / 2 : 3
7.0 / 2: 3.50000000
The warning is in the build, and the two lines of output follow the run. A single real literal in the expression removes both the truncation and the warning.
Choosing the width
An integer that leaves its range is a bug, and the fix is a wider kind, not a check after the fact. Three questions decide the width:
- What is the largest value the variable holds? A byte count over two gigabytes needs int64; a loop index over a million elements does not.
- What is the largest value the arithmetic reaches, not the variable? A sum of a million values of a thousand is a billion, which fits in 4 bytes with a factor of two to spare and not with a factor of twenty.
- Is the value ever passed to a library? A C function that takes an int takes 4 bytes, and the iso_c_binding kind is the one to use at that boundary.
A program that must detect overflow can test before it adds: if (a > huge(a) - b) catches a positive overflow of a + b before it happens.
gfortran can also trap the overflow instead of wrapping it. -ftrapv makes the runtime abort on a signed overflow of an addition, a subtraction or a multiplication:
gfortran -Wall -Wextra -std=f2018 -ftrapv wrap.f90 -o wrap_trap
./wrap_trap
Program received signal SIGABRT: Process abort signal.
The runtime then prints a backtrace whose inner frames are addresses that change on every run, and the shell reports the exit status 134. The flag covers the three operators above and not every way a value can leave its range, so it finds a bug in a test run and does not replace the test in the code: use both.
Exercises
- Print -7 / 2 and floor(-7.0 / 2.0). Which is the floor division?
- Print mod(-7, 2) and modulo(-7, 2). Which one stays positive?
- Make the overflow program build by declaring big as an int64 variable. What does the sum print?
- Write a test that detects the overflow of a + b before the addition happens.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is
-7 / 2in Fortran?Answer
-3
Integer division truncates toward zero, so -3.5 becomes -3.
-
Which function gives a remainder with the sign of the divisor?
Answer
modulo
modulo(-7, 2) is 1, while mod takes the sign of the dividend.
-
What does
mod(7, -2)return?Answer
1
mod keeps the sign of the dividend, so the result is 1.
-
What does the compiler do with
huge(0_int32) + 1_int32?Answer
It reports Error: Arithmetic overflow and stops the build
Both operands are constants, so the overflow is caught at compile time.
-
What happens when a variable overflows at run time?
Answer
The value wraps to the other end of the range without a message
Fortran integer arithmetic wraps, and gfortran has no runtime trap for it.
-
What is
huge(0_int32) + 1computed in variables?Answer
-2147483648, the smallest int32
One past the largest signed value is the smallest signed value.
-
What does this program print?
program p implicit none print *, 7 / 2 + 7.0 / 2 end program pAnswer
6.50000000
7 / 2 is 3, 7.0 / 2 is 3.5, and the sum is the real 6.5.
-
Which warning does a constant integer division produce?
Answer
Warning: Integer division truncated to constant '3' [-Winteger-division]
gfortran reports the truncation of a constant division under -Winteger-division.
-
Why is
int64the right kind for a byte count?Answer
A 4-byte counter wraps past about two gigabytes
The range of the 4-byte type is too small for a large file count.
-
How can a program detect an overflow of
a + bbefore adding?Answer
Test whether a > huge(a) - b
The subtraction stays in range, so the test is safe where the addition is not.
The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev