Familiar syntax, different defaults · 12 min · free lesson

Integer Overflow and Casts

Rust never converts between integer types silently, and overflow is always defined: a panic in debug builds, wrapping in release builds, or exactly the policy you call.

Core idea

Integer types never mix implicitly; choose the overflow policy (checked_, wrapping_, saturating_) and the conversion (From, TryFrom, as) explicitly.

C and Rust, side by side

C Unsigned overflow wraps to 0, (uint8_t)300 keeps the low byte, -1 < 3u is false, and add(INT32_MAX, 1) is undefined behaviour that UBSan reports.
#include <stdint.h>
#include <stdio.h>

static int32_t add(int32_t a, int32_t b) { return a + b; } /* overflow is UB */

int main(void) {
    uint32_t count = 65536, size = 65536;
    uint32_t bytes = count * size;  /* unsigned: wraps to 0, no error */
    uint8_t byte = (uint8_t)300;    /* keeps the low 8 bits: 44 */
    int d = -1;
    unsigned u = 3;
    printf("bytes=%u byte=%u\n", bytes, byte);
    printf("-1 < 3u is %d\n", d < u); /* d converts to UINT_MAX: 0 */
    printf("%d\n", add(INT32_MAX, 1)); /* UBSan: signed integer overflow */
    return 0;
}
Rust Each line chooses its policy: None from checked_mul, deliberate wrapping, a truncating as, a checked conversion, a saturating float cast and an explicit widening.
fn main() {
    let count: u32 = 65_536;
    let size: u32 = 65_536;
    println!("{:?}", count.checked_mul(size));   // None: overflow is a value
    println!("{}", count.wrapping_mul(size));     // 0: wrapping, when you mean it
    println!("{}", 300_i32 as u8);                // 44: `as` truncates integers
    println!("{:?}", u8::try_from(300_i32).ok()); // None: a checked conversion
    println!("{}", 3.9e10_f64 as i32);            // 2147483647: float casts saturate
    let d: i32 = -1;
    let u: u32 = 3;
    println!("{}", i64::from(d) < i64::from(u));  // true: widen both sides yourself
}
What changes
CRust
Signed overflow is undefined; unsigned overflow wraps silently.Overflow panics in debug builds and wraps in release; checked_* makes it a value.
Usual arithmetic conversions mix signed and unsigned silently.Mixed integer types do not compile (E0308); convert with From, TryFrom or as.
An out-of-range float-to-integer conversion is undefined.f64 as i32 saturates, and NaN becomes 0.

Understand it

C's usual arithmetic conversions decide behind your back: in -1 < 3u the int becomes UINT_MAX and the comparison is false, and clang's -Wsign-compare is the only hint. Rust has no integer promotion and no implicit conversion between i32, u32, usize or any other pair. Comparing or adding mixed types is error E0308. Widen with i64::from(d), which cannot fail, or convert with u8::try_from(x), which returns a Result when the value might not fit.

Signed overflow in C is undefined behaviour: UBSan reports signed integer overflow: 2147483647 + 1 cannot be represented in type 'int32_t', and the optimiser may assume it never happens. In Rust overflow is always defined. In the default debug profile arithmetic is checked, and overflow panics with attempt to add with overflow. The release profile turns overflow-checks off, and the same expression wraps in two's complement. Neither is undefined, but a program that depends on either for ordinary values has a bug.

When overflow is possible, say what you want. checked_mul returns None, wrapping_mul wraps on purpose (hashes, checksums), saturating_add clamps at the limit, and overflowing_add returns the wrapped value with a flag. The policy is then visible in the code instead of depending on the build profile.

as remains for deliberate, lossy casts. Between integers it truncates or extends like a C cast: 300_i32 as u8 is 44. From floating point it saturates, and NaN becomes 0, where C is undefined for out-of-range values. Use as when you mean exactly that, and TryFrom when a value that does not fit is an error.

The C habit, written in Rust

This is how the C version usually looks on a first attempt in Rust. Predict what rustc says before you read the explanation.

fn main() {
    let u: u32 = 3;
    let d: i32 = -1;
    println!("{}", d < u);
}

Practise this code in Playground ↗

Try it

Port the commented C functions without their silent wrap and truncation: total_bytes returns None when count * size does not fit in u32, and to_byte returns None for values outside 0..=255.

What success looks like: total_bytes(65_536, 65_536) is None, to_byte(300) and to_byte(-1) are None, and values that fit come back unchanged.

Check your understanding

In C, d < u with int d = -1 and unsigned u = 3 is false. What does rustc do with the same comparison on an i32 and a u32?

Reveal the answer
  1. Rejects it with E0308: you must convert one side yourself
  2. Converts d to u32 and returns false, like C
  3. Converts both to i64 and returns true
  4. Compiles, then panics at run time because d is negative

Rust has no usual arithmetic conversions. i64::from(d) < i64::from(u) states the widening and evaluates to true.

Go deeper

Common misconception: “Overflow in Rust is like unsigned overflow in C: it silently wraps.”

Only in release builds with the default profile, and even there it is a defined wrap rather than undefined behaviour. Debug builds panic. Code that needs wrapping should call wrapping_* so it does not depend on the build profile.

  1. Find the mixed types: Every C expression that mixes signedness or width becomes a compile error in Rust; decide which side to convert.
  2. Pick the policy: For each +, * or - that can exceed the type, choose checked_, wrapping_ or saturating_, or prove the bound.
  3. Separate casts from conversions: Keep as for intended truncation; use TryFrom where an out-of-range value is an error.

Transfer challenge: Write midpoint(lo: u32, hi: u32) -> u32 without (lo + hi) / 2, then test it with u32::MAX - 1 and u32::MAX.

Connections

  • const by Default: Immutable bindings, mut and shadowing
  • Functions Are Expressions: Tail values replace return and the ternary
Side-by-side comparison: the C version on the left, the Rust version on the right, then 3 rows naming what changes.
Integer Overflow and Casts: the same task in C and in Rust, with the differences that matter.
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Integer Overflow and Casts (courseId "rust-for-c-developers", lessonId "c-integer-overflow-and-casts")
Link: https://crabrix.com/learn/rust-for-c-developers/c-integer-overflow-and-casts/
Goal: Integer types never mix implicitly; choose the overflow policy (checked_, wrapping_, saturating_) and the conversion (From, TryFrom, as) explicitly.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-c-developers/c-integer-overflow-and-casts) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.