Strange overflow behavior

Hi!

I’ve stumbled upon a strange (to my point of view) behavior, though maybe I’m missing something in a rust runtime implementation. Following snippet describes the issue:

let mut num1: u8 = 300;
// works fine, just overflows the value
num1 += 1;


let mut num2: u8 = 255;
// panics with 'attempt to add with overflow'
num2 += 1;

So why the handling of such similar cases is different?

In both cases we have an overflow going on, but in the second case rust just panics like it can’t overflow properly, which he just did for num1.

I’m running rustc 1.28.0 on darwin if it will help in any way.

Your first example is overflowed once at compile time. You got a warning about this:

warning: literal out of range for u8
 --> src/main.rs:2:20
  |
2 | let mut num1: u8 = 300;
  |                    ^^^
  |
  = note: #[warn(overflowing_literals)] on by default

At run time, the initial value in num1 is 300 mod 256 (44). Adding one to that is not an overflow.

3 Likes

Bah, it was so simple =( Just missed the warning in the output. Thanks for clarification!

Overflow is only checked in debug builds. This playground example behaves differently if run in debug vs release mode.

1 Like

Why isn't this an error instead of a warning?

There’s an RFC for doing this in Rust 2018: https://github.com/rust-lang/rfcs/pull/2438

I was surprised to find out that there seem to be legitimate (but fringe) cases for this.

3 Likes

I’ve also learned today that Rust supports scientific notation.