Is left-shifting a negative value undefined behavior in Rust?

rust, undefined-behavior

Solution

The Rust Reference has a list of all undefined behavior. Left shifting a signed number beyond the size of the type is not in the list.

Problem

Several operations on integers that yield undefined behavior in C are defined in Rust. A common theme is that they panic in debug mode and have a defined non-panic outcome in release mode. For example, signed integer overflow panics in debug mode, but wraps in release mode. There are also operator variants defined like `wrapping_add()`, `saturating_add()`, etc. But what about shifting a negative value? This is undefined behavior in C. The following test case succeeds in Rust 1.17.0: ``` #[test] fn negative_shift() { let i = -128i8; let j = i << 1; assert_eq!(j, 0); } ``` Although it succeeds it could still be undefined behavior...

Original source