Does the shift of a negative undefined value change in Rust?

Rust defines several operations with integers that give undefined behavior in C. The common theme is that they panic in debug mode and have a certain non-panic result in release mode. For example, copied integer panic overflows in debug mode, but end in release mode. There are also operator variants defined as wrapping_add() , saturating_add() , etc.

But what about offsetting a negative value? This behavior is undefined in C.

The following test example succeeds in Rust 1.17.0:

 #[test] fn negative_shift() { let i = -128i8; let j = i << 1; assert_eq!(j, 0); } 

Although he succeeds, he can still be undefined behavior ...

+5
source share
1 answer

Rust Reference contains a list of all undefined behavior . The left offset of the sign number outside the size of this type is not in the list.

+2
source

All Articles