gpt4 book ai didi

c++ - 对于带移位的循环

转载 作者:行者123 更新时间:2023-12-01 15:07:53 25 4
gpt4 key购买 nike

谁能解释这个for循环是如何工作的? for (bitMask = 0x01; bitMask; bitMask <<= 1)这是我第一次在for循环中遇到这样的语法,并且很想知道循环将如何结束。

最佳答案

如果您获得了无符号 int32变量bitMask。在第32个周期,其位表示为

10000000 00000000 00000000 00000000

然后向左移一位,它溢出,仅保留低32位,因此该值变为0,循环条件变为假。
1 00000000 00000000 00000000 00000000

this bit is discarded

如果 bitMask签名的整数,该怎么办?这是未定义的行为。

C标准(N2716,6.5.7位移位运算符)说:

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2^E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2^E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined



C++标准(N4713,8.5.7 Shift运算符)说:

The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 × 2^E2, reduced modulo one more than the maximum value representable in the result type. Otherwise, if E1 has a signed type and non-negative value, and E1 × 2^E2 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.



我的观点是永远不要使用这种循环,因为我们很容易忘记这仅适用于无符号整数。相反,您应该使用类似以下的方法为每个位生成掩码。

for (int i = 0; i < 32; i++) {
int bitMask = 1 << i;
}

关于c++ - 对于带移位的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62148886/

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