Is it expected that a too large bitshift is undefined behavior in Rust?

心已入冬 提交于 2019-12-10 14:17:39

问题


When you run this code:

#![allow(exceeding_bitshifts)]

fn main() {
    const NUMBER: u64 = 0b_10101010;

    fn print_shift(i: u32) {
        println!("{:b}", NUMBER >> i);
    }

    print_shift(65);
    println!("{:b}", NUMBER >> 65);
}

You see that shifting the bits of a number with a value that exceed the bit length produces different behavior when doing at compile time or runtime.

Is it a normal behavior? Is it documented somewhere? This is not in the list of documented undefined behavior.


回答1:


No, this is not expected, but it is not undefined behavior. This is "just" a bug.

There should be no difference between how the constant is computed at compile time and how the value is computed at runtime. This is a hard problem in general as the machine performing the compilation and the machine running the code might have completely different architectures.


When talking about debug vs release builds, the behavior of "too large" bitshifts is expected, and is also not undefined behavior. The clue is in the error message:

attempt to shift right with overflow

Integer overflow is neither unsafe nor undefined:

The Rust compiler does not consider the following behaviors unsafe, though a programmer may (should) find them undesirable, unexpected, or erroneous.

  • ...
  • Integer overflow

See also:

  • How can integer overflow protection be turned off?


来源:https://stackoverflow.com/questions/46714279/is-it-expected-that-a-too-large-bitshift-is-undefined-behavior-in-rust

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!