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.
Integers wrap around
Section titled “Integers wrap around”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-128255UInt8goes from 0 to 255. One past 255 wraps to 0, and one below 0 wraps to 255.Int8goes 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.
It happens with Int too
Section titled “It happens with Int too”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-1794967296Int32 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.
Does a debug build catch it? No
Section titled “Does a debug build catch it? No”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.
Unsigned subtraction: the classic trap
Section titled “Unsigned subtraction: the classic trap”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:
18446744073709551614That’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.
Literals that don’t fit wrap too
Section titled “Literals that don’t fit wrap too”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 0The 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:
10240The 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.
Edge cases we checked
Section titled “Edge cases we checked”A few more things we tried on Mojo 1.2, in case you run into them:
Int.MINhas no positive partner.-Int.MIN,abs(Int.MIN)andInt.MIN // -1all give backInt.MIN, because the positive value is one too big for anInt.- Floats don’t wrap. A
Float64orFloat32that gets too big becomesinf(infinity).Float16gets there quickly: its largest value is about 65504, soFloat16(60000) + Float16(60000)isinf. - Float to integer out of range gives nonsense.
Int(x)withx = 1e30gave a different meaningless number each time we ran it. - Integer division by zero is unpredictable.
10 // 0,10 / 0and10 % 0withIntvariables printed0in 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.
Checking before it happens
Section titled “Checking before it happens”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:
120Error: Int8 overflow: 150 does not fitInt 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.)
2. Compare against the limit first
Section titled “2. Compare against the limit first”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:
42Error: too big3. Stop at the limit instead (saturate)
Section titled “3. Stop at the limit instead (saturate)”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:
255Without the cap, health += potion would have wrapped to 4, so drinking a potion would nearly kill you.
Practice
Section titled “Practice”1. Predict the output
Section titled “1. Predict the output”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:
44127200 + 100 is 300, and 300 - 256 is 44. Going one below Int8.MIN (-128) wraps around to Int8.MAX (127).
2. A safe score
Section titled “2. A safe score”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:
253255The sum is always correct in an Int, and min stops it at 255 before it’s turned back into a UInt8.
3. Catch the unsigned trap
Section titled “3. Catch the unsigned trap”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: 2Subtracting 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 (
UInt8255 + 1 is0,Int8127 + 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 = 300is44. - Unsigned subtraction below zero gives a huge number, not a negative one.
- Compile-time math has no limit, but storing the result in an
Intcuts it to 64 bits. - Protect yourself: compute in a bigger type and check, compare against
.MAXbefore adding, or cap withmin/max. Floats go toinfinstead of wrapping.
Next up: if…else, making decisions in your code.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Numeric types reference: the “Sharp edges” section covers wrapping, platform-dependent
Intand float-to-int truncation. - Mojo manual: Types: the “Overflow behavior” section for signed and unsigned integers.
- Types and literals cheat sheet: the short list of overflow and literal-wrapping rules.
SIMDAPI docs: how conversions between integer types wrap, with examples.- Two’s complement (Wikipedia): how signed integers are stored, and why they wrap the way they do.