C++ 无符号 Shorts 除法结果为 int

标签 c++ int division unsigned short

为什么二除的结果是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/

相关文章:

C++ 指针/for 循环混淆

c++ - 调用 C++ dll 时发生访问冲突

c - 从 c 中的整数值中抓取位

actionscript-3 - 如何在没有精度错误的情况下正确划分微小的 double 字?

java - 试图设置狗尾部的长度,但由于某种原因它不起作用

java - 程序变慢但计算的数字变小

c++ - 将 printf 语句转换为 cout?

c++ - Gtk+ g_signal_connect() 和 C++ lambda 导致 "invalid cast"错误

c - 该程序工作正常高达 9 位数字和失败在 10 位

c - 是否可以在没有 for 循环的情况下执行“离散”几何和?