Rust removes overflow checks when optimization enabled

why does optimization removes overflow checks?
consider below testcase

fn fibonacci(n: u32) -> u32 {
    let mut f:u32 = 0;
    let mut s:u32 = 1;
    let mut next: u32 =f+s;    
    for _ in 1..n {
                f = s;
                s= next;

fn main() {
$rustc -C opt-level=1

$rustc -C opt-level=0
thread 'main' panicked at 'attempt to add with overflow',
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.

Basically because no one has found a way to make it fast, and the consequences of overflow are more benign than would be e.g. those of removing array bound checks (panic or logical stupidity vs undefined behavior).

1 Like

You can have your overflow checks with optimization.

Add this to your Cargo.toml

overflow-checks = true

And build with cargo.

I guess there is a rustc command line option to do the same, I have no idea what it is.

In my limited tests switching on overflow checks had a 15% performance hit. That was for an FFT that is doing a lot of maths using fixed point arithmetic. I wanted overflow flow checks enabled to be sure my fixed point maths was not blowing up.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.