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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With