是否期望太大的移位是Rust中未定义的行为? [英] Is it expected that a too large bitshift is undefined behavior in Rust?

查看:169
本文介绍了是否期望太大的移位是Rust中未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行此代码时:

#![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.

推荐答案

不,这不是预期,但这是未定义的行为. 这只是"一个错误.

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

整数溢出也不是不安全的也未定义:

Rust编译器不会将以下行为视为不安全, 尽管程序员可能(应该)发现它们不受欢迎,出乎意料,或者 错误的.

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

  • ...
  • 整数溢出

另请参阅:

这篇关于是否期望太大的移位是Rust中未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆