0

(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 ?

norbjd
  • 10,166
  • 4
  • 45
  • 80

1 Answers1

2

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.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
  • I should have updated my Rust version before posting... Thanks for the answer ! – norbjd Jul 23 '20 at 13:37
  • And by the way, to be fully correct, this was not a warning but an error. – norbjd Jul 23 '20 at 13:41
  • @norbjd: `arithmetic_overflow` is a warning (a lint); you may choose to _report it as an error_, using deny, but it doesn't change its nature (being a warning) and therefore the fact that it is only reported on a best effort basis. – Matthieu M. Jul 23 '20 at 13:55