为什么二除的结果是unsigned short
类型 int
在 C++ 中?我创建了一个示例,可以轻松地在例如中进行测试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;
}
最佳答案
来自隐式转换/数字促销/Integral promotion :
prvalues of small integral types (such as char) may be converted to prvalues of larger integral types (such as int). In particular, arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable.
[编辑]来自同一页面:
unsigned char, char8_t (since C++20) or unsigned short can be converted to int if it can hold its entire value range, and unsigned int otherwise
OP 的情况属于(突出显示的)情况,因为目标平台上的 sizeof int = 4 > 2 = sizeof unsigned int
(根据发布的链接)。如果情况并非如此(即 int
无法保存整个范围的 unsigned int
值,例如例如,在 sizeof int == sizeof Short
的平台上),那么两个操作数都会通过积分提升规则提升为 unsigned int
,并且除法的结果将是相反,unsigned int
。
关于C++ 无符号 Shorts 除法结果为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62641364/