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 中设置)。要搜索的关键字是“整数提升”
推荐阅读
- sql - 输入末尾的 PostgreSQL 语法错误不知道为什么
- c++ - 将多类型向量的字符串部分与一种类型向量进行比较并擦除重复项的更快方法
- javascript - 将消息同步发布到 worker_thread。发送线程阻塞,worker_thread 解除阻塞
- matlab - 在 Julia 中将复数向量转换为稀疏对角线数组
- sql - 关于服务器版本的 MySQL 语法错误的解决方案?
- r - “x”熔岩错误中的无限值或缺失值
- php - 趋势查询 Laravel
- opengl - 创建渲染器时 SDL 终止
- javascript - 寻求帮助以使 npm/pdfjs-dist 与 Webpack 和 Django 一起工作
- r - R:在 Plotly 中注释条形图