Panicked at 'arithmetic operation overflowed'


#1

Hi.the following code will be panicked:

fn main(){
     
    let h = 875770417_u32;
    println!("{}--{}--{}",h,0x1e35a7bd,0x1e35a7bd as usize);
    println!("{}",h as usize*0x1e35a7bd);
    println!("{:?}",h*0x1e35a7bd_u32);
    println!("{:?}",h*0x1e35a7bd);
}

Output:

875770417--506832829--506832829
443869198002619693
thread '<main>' panicked at 'arithmetic operation overflowed', <anon>:6
playpen: application terminated with error code 101

but in C++

#include <stdio.h>
#include <stdint.h>

int main()
{
    uint32_t a=875770417;
    uint32_t b = 0x1e35a7bd;
    printf("%d",a*b );
	return 0;
}

It’s works just fine, output:“296682797”. How to make it works in Rust.


#2

The exact value of the multiplication is too large to be stored in a u32, i.e. it overflows. This is often a bug, and so Rust will detect such overflows in debug builds and panic, to indicate to the programmer that there may be something wrong. Of course, it is not always a bug, and so when the wrapping (i.e. modulo 232) behaviour is desired, there are wrapping_* methods, e.g. wrapping_mul.

fn main(){
    let h = 875770417_u32;
    println!("{}--{}--{}", h, 0x1e35a7bd, 0x1e35a7bd as usize);
    println!("{}", h as usize * 0x1e35a7bd);
    println!("{:?}", h.wrapping_mul(0x1e35a7bd_u32));
    println!("{:?}", h.wrapping_mul(0x1e35a7bd));
}

prints

875770417--506832829--506832829
443869198002619693
296682797
296682797

If a lot of operations that want wrapping are being performed, there’s also the Wrapping type which allows using the arithmetic operators, e.g. let h = Wrapping(875770417); ... h * Wrapping(0x1e35a7bd).

(It doesn’t panic when you cast to usize first, because you’re on a 64-bit computer (hence usize is 64 bits) and the result of the multiplication can be stored in 64 bits.)


#3

:slightly_smiling:thanks for your quick response,gotcha