Skip to content

Mojo Integer Overflow

Every integer type in Mojo has a fixed number of bits, so it has a smallest and a largest value. Overflow is what happens when a result doesn’t fit: UInt8 can hold up to 255, so what is 255 + 1? Python never has this problem, because its int grows as needed. In Mojo you need to know the answer, because the program won’t tell you. This page shows what Mojo 1.2 actually does, based on the official docs and programs we ran ourselves, and how to protect your code.

When a result is too big (or too small), Mojo wraps around to the other end of the range, like a car’s odometer rolling over from 999999 to 000000:

def main():
var level: UInt8 = 255
level += 1
print(level)
var temp: Int8 = 127
temp += 1
print(temp)
var stock: UInt8 = 0
stock -= 1
print(stock)

Output:

0
-128
255
  • UInt8 goes from 0 to 255. One past 255 wraps to 0, and one below 0 wraps to 255.
  • Int8 goes from -128 to 127. One past 127 wraps to -128: the biggest positive number turns into the most negative one.

There’s no error and no warning. The program just carries on with the wrong number. The numeric types reference says it directly: integer arithmetic wraps on overflow using two’s complement, and Mojo doesn’t trap on overflow.

Int has 64 bits on most computers, so overflow is much rarer, but it works the same way:

def main():
var x = Int.MAX
print(x)
print(x + 1)
var views: Int32 = 2_000_000_000
views += 500_000_000
print(views)

Output:

9223372036854775807
-9223372036854775808
-1794967296

Int32 tops out at about 2.1 billion, so adding half a billion to 2 billion gives a negative number. A counter like this (views, bytes, milliseconds) is exactly where overflow bugs hide: it works for months and then one day the number gets big enough.

In some languages (Rust, for example) a debug build stops the program on overflow. We checked whether Mojo 1.2 does anything like that. We ran the overflowing programs above with mojo run, and built them with mojo build using -O0, -O3, --debug-level full and -D ASSERT=all. Every build wrapped the same way, with no error. (Tested with Mojo 1.2.0 on Linux, x86-64.)

So don’t count on a special build mode to find overflow for you. You have to check yourself, as shown below.

Subtracting a bigger unsigned number from a smaller one doesn’t give a negative number, because unsigned types can’t be negative. It wraps to a huge number instead:

def main():
var have: UInt = 3
var need: UInt = 5
print(have - need)

Output:

18446744073709551614

That’s UInt.MAX - 1. If this value is then used as a size or a count, things go wrong far away from the real mistake. This is one reason the official docs suggest Int (signed) for counts and indexes: a negative result is at least easy to spot.

You might expect the compiler to reject var a: Int8 = 300, since it can see that 300 doesn’t fit. In Mojo 1.2 it doesn’t. The literal wraps, silently:

def main():
var a: Int8 = 300
var b: UInt8 = -1
var c: UInt8 = 256
print(a, b, c)

Output:

44 255 0

The types and literals cheat sheet documents this: integer literals wrap silently, so var b: Int8 = 300 is 44. The same goes for converting a variable to a smaller type with Int8(x) or UInt8(x), as you saw in Mojo Type Conversion.

Compile-time math is the one place where whole numbers have no limit. comptime BIG = 2 ** 100 is fine. But the moment you put it into an Int variable, it gets cut down to 64 bits:

def main():
comptime BIG = 2 ** 100
print(BIG // 2 ** 90)
var x = BIG
print(x)

Output:

1024
0

The first line is done entirely by the compiler, so it’s exact. In the second, 2 ** 100 has to fit in 64 bits, and all of its set bits are above bit 63, so what’s left is 0.

A few more things we tried on Mojo 1.2, in case you run into them:

  • Int.MIN has no positive partner. -Int.MIN, abs(Int.MIN) and Int.MIN // -1 all give back Int.MIN, because the positive value is one too big for an Int.
  • Floats don’t wrap. A Float64 or Float32 that gets too big becomes inf (infinity). Float16 gets there quickly: its largest value is about 65504, so Float16(60000) + Float16(60000) is inf.
  • Float to integer out of range gives nonsense. Int(x) with x = 1e30 gave a different meaningless number each time we ran it.
  • Integer division by zero is unpredictable. 10 // 0, 10 / 0 and 10 % 0 with Int variables printed 0 in most of our tests, but in another test a zero that only turned up while the program ran crashed it instead. The docs don’t describe either result, so always check for zero before dividing.

Since Mojo won’t warn you, the fix is to check the numbers yourself when they could get big. Three common ways:

1. Do the math in a bigger type, then check

Section titled “1. Do the math in a bigger type, then check”

For small types, convert to Int, compute, and check the result against the small type’s .MIN and .MAX. Here the function raises an error when the result doesn’t fit:

def add_int8(a: Int8, b: Int8) raises -> Int8:
var wide = Int(a) + Int(b)
if wide > Int(Int8.MAX) or wide < Int(Int8.MIN):
raise Error("Int8 overflow: ", wide, " does not fit")
return Int8(wide)
def main():
try:
print(add_int8(100, 20))
print(add_int8(100, 50))
except e:
print("Error:", e)

Output:

120
Error: Int8 overflow: 150 does not fit

Int has plenty of room for the sum of two Int8 values, so wide is always correct. Only then do you decide whether it fits. (raises, raise and try get their own lessons: Mojo Errors and Mojo Try/Except.)

For Int itself there’s no bigger everyday type, so check before you add. If b is positive, a + b overflows exactly when a > Int.MAX - b, and that subtraction can’t overflow:

def safe_add(a: Int, b: Int) raises -> Int:
if b > 0 and a > Int.MAX - b:
raise Error("too big")
if b < 0 and a < Int.MIN - b:
raise Error("too small")
return a + b
def main():
try:
print(safe_add(40, 2))
print(safe_add(Int.MAX, 1))
except e:
print("Error:", e)

Output:

42
Error: too big

Sometimes the right answer is “as high as it goes”, like a volume knob or a health bar. Compute in a bigger type and cap the result with min (and max for the bottom):

def main():
var health: UInt8 = 250
var potion: UInt8 = 10
var total = Int(health) + Int(potion)
health = UInt8(min(total, Int(UInt8.MAX)))
print(health)

Output:

255

Without the cap, health += potion would have wrapped to 4, so drinking a potion would nearly kill you.

Without running it, work out what this prints. Then run it to check.

def main():
var a: UInt8 = 200
var b: UInt8 = 100
print(a + b)
var c: Int8 = -128
c -= 1
print(c)

Hint: UInt8 wraps after 255 back to 0; Int8 wraps below -128 to 127.

Show solution

Output:

44
127

200 + 100 is 300, and 300 - 256 is 44. Going one below Int8.MIN (-128) wraps around to Int8.MAX (127).

Write a function add_points(score: UInt8, points: UInt8) -> UInt8 that adds the points but never goes past 255. Test it with 250 + 3 and 250 + 10.

Hint: compute in Int, then cap with min(..., Int(UInt8.MAX)).

Show solution
def add_points(score: UInt8, points: UInt8) -> UInt8:
var total = Int(score) + Int(points)
return UInt8(min(total, Int(UInt8.MAX)))
def main():
print(add_points(250, 3))
print(add_points(250, 10))

Output:

253
255

The sum is always correct in an Int, and min stops it at 255 before it’s turned back into a UInt8.

have and need are UInt. Print missing: 2 when need is bigger than have, and enough otherwise. Test with have = 3 and need = 5.

Hint: compare the two values before you subtract.

Show solution
def main():
var have: UInt = 3
var need: UInt = 5
if need > have:
print("missing:", need - have)
else:
print("enough")

Output:

missing: 2

Subtracting the smaller value from the bigger one can’t wrap, so need - have is always safe inside that if.

  • In Mojo 1.2, integer math wraps around on overflow (UInt8 255 + 1 is 0, Int8 127 + 1 is -128). It doesn’t stop or warn.
  • That’s true in every build mode we tried, including debug info and -D ASSERT=all.
  • Literals and narrowing conversions wrap silently too: var a: Int8 = 300 is 44.
  • Unsigned subtraction below zero gives a huge number, not a negative one.
  • Compile-time math has no limit, but storing the result in an Int cuts it to 64 bits.
  • Protect yourself: compute in a bigger type and check, compare against .MAX before adding, or cap with min/max. Floats go to inf instead of wrapping.

Next up: if…else, making decisions in your code.

Quick check

1. With var x: UInt8 = 255, what is x after x += 1?
2. Does building with -D ASSERT=all make Mojo 1.2 catch integer overflow?
3. What does var a: Int8 = 300 do?
4. With var a: UInt = 3 and var b: UInt = 5, what is a - b?
5. What is a safe way to add two Int8 values?