fn main() {
let num: u8 = 255;
let num2: u8 = num + 1;
println!("{}, {}", num, num2);
}
When $ cargo build --release
, this code doesn't make compile error.
And $ cargo run
, make runtime error.
thread 'main' panicked at 'attempt to add with overflow', src/main.rs:3:20 note: run with
RUST_BACKTRACE=1
environment variable to display a backtrace
This is okay. But what I don't understand is the situation below. When I delete println line, it makes compile error.
fn main() {
let num: u8 = 255;
let num2: u8 = num + 1;
}
$ cargo build --release
error: this arithmetic operation will overflow
--> src/main.rs:3:20
|
3 | let num2: u8 = num + 1;
| ^^^^^^^ attempt to compute `u8::MAX + 1_u8`, which would overflow
|
= note: `#[deny(arithmetic_overflow)]` on by default
Why does integer overflow sometimes cause compilation errors or runtime error?