C++无符号短裤的划分导致 int

C++ division of unsigned shorts results in int

本文关键字:int 划分 无符号 C++      更新时间:2023-10-16

为什么C++中两个intunsigned short的划分结果?我创建了一个可以轻松测试的示例,例如 http://cpp.sh/

// Example program
#include <iostream>
#include <string>
#include <typeinfo>
int main(){
unsigned short a = 1;
unsigned short b = 1;
auto c = a/b;
std::cout<<"result of dividing unsigned shorts is: "<<typeid(c).name()<<std::endl;
}

来自隐式转换/数字提升/积分提升:

小整型(如 CHAR(的 pr值可以转换为较大整型(如 int(的 pr值。特别是算术运算符不接受小于 int 的类型作为参数,并且在左值到右值转换后自动应用积分提升(如果适用(。


[编辑] 从同一页面:

无符号字符、char8_t(自 C++20 以来(或 无符号 short 如果可以保存其整个值范围,则可以转换为 int, 否则将无符号 int

转换为

OP 的案例属于(突出显示的(案例,因为sizeof int = 4 > 2 = sizeof unsigned int在目标平台上(根据发布的链接(。如果不是这种情况(即int不能容纳整个unsigned int值范围,例如在sizeof int == sizeof short的平台上(,那么两个操作数都会被积分提升规则提升为unsigned int,而除法的结果将是unsigned int,而是