Beginner trying to understand integer overflow

#1

Beginner here.
Look at following code:

   fn main() {
      let x: u8 = 255;
      println!("The value of x is {}.", x + 1); 
   }

Result is panic message.
My question is:
The range of x in this case should be from 0 ~ 255.
x is defined. But I haven’t defined x + 1
What about the range of x + 1 ? The same as x ?

I am asking because if the code is like this

fn main() {
    let mut x: u8 = 255;
    x = x + 1;

    println!("The value of x is {}.", x);
}

Then I can understand it.

#2

The Add impl is this one: https://doc.rust-lang.org/std/primitive.u8.html#impl-Add<u8>

Because x is a u8, the 1 is inferred to be u8, and the output is also u8.

2 Likes
#3

I’ll also note that the panic is due to the compiler checking for overflows. In the release mode of the compiler (overflow-checks=false), this does not panic, but instead will wrap around and print The value of x is 0. (playground)

1 Like