Arithmetic overflow expected but does not occur

354 views Asked by At

(I'm using Rust 1.44.1)

The following example fails to build (debug mode) because of arithmetic overflow (and I understand why) :

fn main() {
    let i: u8 = 255 + 1;
}
error: this arithmetic operation will overflow
 --> src/main.rs:2:17
  |
2 |     let i: u8 = 255 + 1;
  |                 ^^^^^^^ attempt to add with overflow
  |
  = note: `#[deny(arithmetic_overflow)]` on by default

While this example builds correctly :

fn main() {
    let i: u8 = 255;
    let _j: u8 = i + 1;
}

Since i is immutable, I would have expected the same error as the first example.

Am I missing something or this is something not handled by the compiler ?

1

There are 1 answers

3
Matthieu M. On BEST ANSWER

First of all, it should be noted that warnings are emitted on a best effort basis.

A good policy for warnings, in general, is:

  • To avoid false positives: nothing more annoying for a user than to be warned there is an issue when there is none.
  • And therefore possibly have false negatives: situations that should have triggered the warning, but were not detected.

Also, due to performance considerations, analysis may be limited to the most basic patterns, which once again means that some occurrences will not be detected.


With that said, the warning is correctly triggered on Rust 1.45.

As a result, I believe you have simply hit a limitation of the 1.44.1 version.