gpt4 book ai didi

c++ - bool 值的左移和右移

转载 作者:太空狗 更新时间:2023-10-29 21:39:23 26 4
gpt4 key购买 nike

我正在尝试了解整数提升如何与算术移位运算符一起使用。特别是,我想知道 a, b, c, d, e, f, g, h 的哪些值是根据 C++14 标准准确定义的,哪些可以依赖在平台/硬件/编译器上(假设 sizeof(int) == 4)。

int a = true << 3;
int b = true >> 3;

int c = true << 3U;
int d = true >> 3U;

int e = true << 31;
int f = true >> 31;

int g = true << 31U;
int h = true >> 31U;

最佳答案

来自 [expr.shift]:

The type of the result is that of the promoted left operand. The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.

移位 bool 的结果类型始终是 int,无论右侧是什么。我们永远不会移动至少 32 或负数,所以我们在所有方面都没有问题。

对于左移 (E1 << E2):

Otherwise, if E1 has a signed type and non-negative value, and E1×2E2 is representable in the corresponding unsigned type of the result type, then that value, converted to the result type, is the resulting value; otherwise, the behavior is undefined.

1×231 可以用 unsigned int 表示,这是我们正在做的最大的左移,所以我们在所有帐户上都可以。

对于右移 (E1 >> E2):

If E1 has a signed type and a negative value, the resulting value is implementation-defined.

E1 永远不会是负数,所以我们也没有问题!任何地方都没有未定义或实现定义的行为。

关于c++ - bool 值的左移和右移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33110423/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com