Beginner trying to understand integer overflow

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.

The Add impl is this one: u8 - Rust

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


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

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.