移位后返回不同结果的等效语句的解释
Explanation for equivalent looking statements returning different results after bitshift
寻找对这里发生的事情的理解,因为两个陈述看起来相同。
因此,虽然 c >> 1
输出符合我的预期,但就地移动包装的 uint 会改变结果。
#include <stdio.h>
#include <stdint.h>
int main() {
uint16_t a, b, c;
a = 20180;
b = 4106;
c = b - a;
printf("%hu\n", c >> 1);
printf("%hu\n", (b - a) >> 1);
return 0;
}
这会打印:
24731
57499
是什么导致了这种行为?
谢谢。
“就地”操作将 a 和 b 提升为 int,结果也将是一个 int,然后您将其移位。
在您对 c = b - a 的赋值中,该操作首先被提升为 int 操作,执行,然后类型转换回 uint(将在 c 中设置)。
要搜索的关键字是“整数提升”
寻找对这里发生的事情的理解,因为两个陈述看起来相同。
因此,虽然 c >> 1
输出符合我的预期,但就地移动包装的 uint 会改变结果。
#include <stdio.h>
#include <stdint.h>
int main() {
uint16_t a, b, c;
a = 20180;
b = 4106;
c = b - a;
printf("%hu\n", c >> 1);
printf("%hu\n", (b - a) >> 1);
return 0;
}
这会打印:
24731
57499
是什么导致了这种行为?
谢谢。
“就地”操作将 a 和 b 提升为 int,结果也将是一个 int,然后您将其移位。 在您对 c = b - a 的赋值中,该操作首先被提升为 int 操作,执行,然后类型转换回 uint(将在 c 中设置)。 要搜索的关键字是“整数提升”