K
Spilled coffee
Photo by Tyler Nix on Unsplash

Does integer division overflow?

What's integer overflow?

In computer programming, an integer overflow occurs when an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of digits – either higher than the maximum or lower than the minimum representable value. — Wikipedia — Integer overflow

As you may know, addition of two integer numbers can overflow. For example addition of two int8 number 127 and 1 overflows, and doesn't return mathematically correct answer.

package main

import "fmt"

func main() {
        var i, j int8 = 127, 1
        fmt.Printf("127 + 1 = %d", i+j)
}

This Go programme outputs 127 + 1 = -128. For subtraction, if you think about 127 - (-1), this is going to overflow as this is the equivalent expression to the addition we just saw.

Likewise, multiplication of two integer numbers can overflow.

package main

import "fmt"

func main() {
        var i, j int8 = 64, 2
        fmt.Printf("64 * 2 = %d", i*j)
}

This outputs 64 * 2 = -128.

The reason is because 127 is the biggest number int8 can represent and any calculation resulting in bigger number than this overflows returning unexpected result.

Here is a question: Can division of two integer numbers ever overflow? If yes, which combination of two integers make it happen?

Integer division overflow

From mathematical point of view, if the divisor is either bigger than or equal to 1, or smaller than or equal to -1, the absolute value of the quotient is never going to be bigger than that of the dividend, and for any int8 number this condition is satisfied. So it doesn't seem possible to make overflow happen with two int8 numbers.

…However, yes it is possible, as you may have guessed.

What do you think is the output of this Go programme?

package main

import "fmt"

func main() {
        var i, j int8 = -128, -1
        fmt.Printf("-128 / -1 = %d", i/j)
}

Mathematically correct answer is 128…but wait, wasn't the biggest number int8 can represent 127??

That means this calculation overflows and the output is -128 / -1 = -128.

The reason why this happens is while int8 can represent 2^8 = 256 different numbers, 0 has to be included, which means odd number 255 is left to represent both positive and negative numbers. Most of the computing systems adopt a technique called two's complement to represent signed numbers1 and with that technique int8 is going to have 127 positive numbers and 128 negative numbers.

As a result by dividing the biggest negative number by -1, we can cause overflow in integer division.

I'd like to know more of this kind of "fun facts", so please share if you know. In the next post I'd like to talk about what two's complement is, and why it is so widely used in the computing systems.

Footnotes

  1. Signed numbers: Numbers that consist of both positive and negative numbers