Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 132 ยท Variables and Types

Integer Overflow and Arithmetic

Understand Rust integer overflow - panics in debug builds, wrapping in release, checked_, wrapping_, saturating_ and overflowing_ methods, Wrapping, division, rem_euclid, abs_diff and NaN.

Every integer type has a fixed range. A u8 holds 0 to 255; a calculation such as 255 + 1 has no u8 result. What should the program do? C silently wraps unsigned numbers and treats signed overflow as undefined behavior, which has caused real security holes. JavaScript quietly switches to floating point and loses precision. Rust makes you choose, and its defaults are designed to catch mistakes early.

This lesson explains what happens when arithmetic leaves the range of a type, the four families of methods for saying exactly what you want (checked_, wrapping_, saturating_, overflowing_), the Wrapping wrapper, and the other places where arithmetic has sharp edges: integer division, the remainder operator with negative numbers, subtraction on unsigned numbers, and the strange behavior of NaN in float math. You should know the number types from Integers, Floats, bool and char.

What happens by default

The behavior depends on how the program was compiled:

  • In a debug build (cargo build, the default while developing), overflow panics with the message attempt to add with overflow (or subtract, multiply, and so on).
  • In a release build (cargo build --release), overflow checks are off for speed and the result wraps around in two's complement: 255 + 1 in a u8 becomes 0.

This is controlled by the setting overflow-checks, and you can switch it on in release builds too through the [profile.release] section of Cargo.toml. Our online editor compiles with overflow checks on, so everything you run here behaves like a debug build.

The key point: wrapping in release mode is defined (not undefined behavior as in C), but it is almost never what you meant. Code that relies on silent wrapping in release mode and panics in debug mode is a bug. When you want wrapping, say so explicitly with a method.

The compiler even tries to spot the overflow before running anything:

Rust The compiler sees the overflow (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The output is error: this arithmetic operation will overflow, with the note attempt to compute `u8::MAX + 1_u8`, which would overflow, and it comes from the deny-by-default lint arithmetic_overflow. The lint only works when the values are obvious at compile time. When the numbers come from input or from a function argument, the program compiles and panics at run time:

Rust A run-time overflow panic (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You see level = 251 up to level = 255, and then the panic attempt to add with overflow with the file, line and column of the value + 1 expression, and exit code 101. In a release build the same program would print 0, 1, 2 and so on without complaint. Reading this panic message is a skill worth having; Panics says more.

Choosing the behavior: four method families

Every integer type has methods that name the behavior you want, independent of build mode. Each family has variants for add, sub, mul, div, pow, neg, abs, shifts and more.

Prefix On overflow it... Returns
checked_ gives up Option<T> (None on overflow)
wrapping_ wraps around (modular arithmetic) T
saturating_ sticks at MIN or MAX T
overflowing_ wraps and tells you it did (T, bool)
Rust All four families side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Look at each result.

  • 250 + 10 in a u8 is 260, which does not fit. checked_add returns None; with 5 it returns Some(255). wrapping_add gives 4 (260 minus 256). saturating_add gives 255. overflowing_add returns (4, true): the wrapped value plus a flag.
  • With i8, -100 - 100 is -200: None, saturates to -128, or wraps to 56.
  • 3_u32.pow(30) is 205,891,132,094,649, far too big for u32: None with checked_pow, or 4294967295 with saturating_pow.
  • i32::MIN has no positive counterpart, because the range is -2,147,483,648 to 2,147,483,647. So abs overflows: wrapping_abs returns i32::MIN again and checked_abs returns None. A famous trap: even abs can overflow.

When to use which

  • checked_ when overflow is an error condition you want to detect: totals, quantities, sizes of allocations, input from users. It composes well with ? and ok_or in functions that return Result.
  • saturating_ when "stay at the limit" is the right behavior: volume controls, health points, color channels, counters that should stick at the maximum.
  • wrapping_ when modular arithmetic is the goal: hash functions, checksums, pseudo-random number generators, ring-buffer indices, cryptographic primitives.
  • overflowing_ when you need to know and want the wrapped value, for example when implementing multi-word big-integer arithmetic with carries.

A realistic checked calculation returns a Result, so the caller can decide what to do:

Rust Checked arithmetic in a function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first call returns Ok(5997), and the second returns an Err with the message. No panic, no silent garbage.

A legitimate use of wrapping: hashing

Wrapping is exactly what you want in a hash function. This is the 32-bit FNV-1a hash, which multiplies by a prime and lets the product wrap around:

Rust FNV-1a hash with wrapping_mul

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

If we wrote hash * 0x0100_0193, the very first multiplication would panic in a debug build. By using wrapping_mul, we state clearly that overflow is intended, and the program behaves the same in debug and release builds. The hash of the empty string is the starting value, 811c9dc5.

The Wrapping and Saturating types

If you do a lot of wrapping math, writing .wrapping_add(...) everywhere is noisy. The wrapper std::num::Wrapping<T> makes the ordinary operators +, -, * wrap. Since Rust 1.74 there is also std::num::Saturating<T> which saturates:

Rust Wrapping and Saturating wrappers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

250 + 10 wraps to 4 and then 4 * 2 is 8. The saturating counter stops at 255. The last loop is a tiny linear congruential generator, the classic way to make pseudo-random numbers without a crate: the multiplication is supposed to overflow and wrap. The inner number is reached with .0.

Division and remainder

Integer division has its own rules, and two failures.

Rust Integer division and remainder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

  • 7 / 2 is 3 and -7 / 2 is -3: the quotient is truncated toward zero, not rounded down.
  • The % operator is a remainder, not a mathematical modulo. Its sign follows the left operand: -7 % 3 is -1, not 2. That surprises people who index into a ring: -1 % 24 is -1, an invalid index.
  • rem_euclid always returns a result between 0 and the divisor, so (-1).rem_euclid(24) is 23. div_euclid is the matching quotient (it rounds so that a == b * a.div_euclid(b) + a.rem_euclid(b)). Use rem_euclid for wrap-around indices, clock arithmetic and hash buckets.
  • abs_diff returns the absolute difference as the unsigned type, with no overflow possible: 10_u32.abs_diff(15) is 5 even though 10 - 15 would underflow, and (-3_i32).abs_diff(4) is 7 as a u32.

Dividing by zero is always an error: an integer division by zero panics with attempt to divide by zero (in every build mode), and so does % 0. The one other failure is i32::MIN / -1, since the true answer, +2,147,483,648, does not fit; it panics with attempt to divide with overflow. checked_div handles both cases by returning None.

The unsigned subtraction trap

Because unsigned numbers cannot be negative, subtraction below zero is an overflow. It is the most common overflow in practice, as it appears in code that computes with lengths and indices:

Rust Unsigned underflow (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The program panics with attempt to subtract with overflow. Safe versions are wanted.saturating_sub(items.len()), items.len().checked_sub(wanted) or an if wanted > items.len() check before subtracting. A related loop bug: for i in 0..v.len() - 1 panics for an empty vector, because 0 - 1 underflows. Write for i in 1..v.len() or use iterators and windows(2).

Floating-point arithmetic

Floats do not overflow in the integer sense. They follow IEEE 754: results too large become infinity, invalid operations produce NaN, and nothing panics.

Rust inf, NaN and their rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

  • f64::MAX * 2.0 is inf. Infinity compares correctly and propagates.
  • NaN is unordered: nan == nan, nan < 1.0 and nan > 1.0 are all false. Test with is_nan().
  • max and min ignore a NaN operand and return the other number, which can hide a bug: f64::NAN.max(1.0) is 1.
  • Plain sort_by(|a, b| a.partial_cmp(b).unwrap()) would panic as soon as a NaN appears. total_cmp defines a total order (negative NaN first, positive NaN last), so the sort never fails. The result puts NaN at the end.
  • 0.0 == -0.0 is true, but 1.0 / -0.0 is -inf; the two zeros differ in sign.
  • sqrt of a negative number is NaN; it does not panic.

The takeaway: NaN spreads silently through a calculation. If a final result is NaN, trace back to the first invalid operation (a division 0.0 / 0.0, sqrt of a negative value, inf - inf). Validate float inputs at the boundary of your program, as discussed in Result.

For money, never use floats. Store integer cents (or a decimal type from a crate) and use checked_ arithmetic. Floating point cannot represent 0.10 exactly, and rounding errors accumulate in totals.

Common mistakes

  • Relying on release-mode wrapping by accident. Write wrapping_* when you mean it.
  • Subtracting from a usize without checking (len() - 1 on an empty collection).
  • Using % for wrap-around of negative numbers; use rem_euclid.
  • Assuming abs() is always safe: i32::MIN.abs() overflows.
  • Comparing floats with ==, or sorting floats with partial_cmp().unwrap() when NaN is possible.
  • Testing only in release mode, or only with small numbers. Run tests in debug mode, where overflow checks catch bugs early.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does 255_u8 + 1 do at run time in a debug build (overflow checks on)?

    Debug builds check arithmetic and panic. A release build would wrap to 0 instead. Use checked_, wrapping_ or saturating_ methods to choose the behavior explicitly.
  2. 2. Which method returns an Option that is None on overflow?

    checked_add returns Option<T>. overflowing_add returns a tuple (value, did_overflow), while wrapping_add and saturating_add return plain values.
  3. 3. What is (-7_i32) % 3 in Rust?

    The % operator is a remainder whose sign follows the dividend. (-7).rem_euclid(3) is 2 if you want a result in 0..3.
  4. 4. Why is v.len() - 1 risky?

    usize is unsigned. 0 - 1 overflows, so it panics in debug and wraps to a huge number in release. Use checked_sub, saturating_sub or check emptiness first.
  5. 5. What does f64::NAN == f64::NAN evaluate to?

    NaN is not equal to anything, including itself. Use is_nan() to test for it.

Summary

  • Overflow panics in debug builds and wraps in release builds; our editor behaves like a debug build. Obvious cases are caught at compile time by the arithmetic_overflow lint.
  • Pick the behavior explicitly: checked_ (returns Option), wrapping_ (modular), saturating_ (clamps) and overflowing_ (value and flag).
  • Use Wrapping<T> and Saturating<T> when many operations should share one behavior; wrapping is right for hashes and generators.
  • Integer division truncates toward zero, % keeps the sign of the dividend, rem_euclid gives a non-negative result, and division by zero panics.
  • Unsigned subtraction below zero (len() - 1) is a frequent bug; abs_diff, checked_sub and saturating_sub avoid it.
  • Floats never panic: they produce inf and NaN; NaN != NaN, so use is_nan() and total_cmp.

Next: Type Conversion and Casting shows how to move values between numeric types safely.