无符号短裤的 C++ 除法结果为 int

C++ division of unsigned shorts results in int

为什么C++中int类型的两个unsigned 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;
}

来自隐式转换/数字促销/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(根据发布的 link)。如果 not 是这种情况(即 int 可以 not 保持 unsigned int 值的整个范围,例如在 sizeof int == sizeof short) 的平台上,两个操作数将通过整数提升规则提升为 unsigned int,除法的结果将是 unsigned int,而不是