首页 > 解决方案 > 位移后返回不同结果的等效语句的解释

问题描述

寻找对这里发生的事情的理解,因为这两个陈述看起来都是一样的。

因此,虽然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

是什么导致了这种行为?

谢谢。

标签: cbit-shift

解决方案


“就地”操作将 a 和 b 提升为 int,结果也将是一个 int,然后您将其转换。在 c = b - a 的赋值中,操作首先被提升为 int 操作,执行,然后类型转换回 uint(在 c 中设置)。要搜索的关键字是“整数提升”


推荐阅读