Why is the result of the division of two unsigned short
of type int
in C++? I have created an example which can easily be tested in e.g. 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;
}
From Implicit conversions / Numeric promotions / 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.
[ EDIT ] From the same page:
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's case falls into the (highlighted) case since sizeof int = 4 > 2 = sizeof unsigned int
on the target platform (according to the posted link). Had this not been the case (i.e. an int
could not hold the entire range of unsigned int
values, for example on platforms where sizeof int == sizeof short
) then both operands would have been promoted to unsigned int
by the integral promotion rules, and the result of the division would have been unsigned int
, instead.