I use gcc 4.8.3 under fedora 19 64bits
unsigned u1=10, u2=42;
unsigned short us1=10, us2=42;
int main() {
cout << "u1-u2="<<u1-u2<<", us1-us2="<<us1-us2<<endl;
}
Result : u1-u2=4294967264, us1-us2=-32
The << operator seems to interpret the result of the second operation as a signed short whereas it interprets the result of the first operation as an unsigned int
For unsigned ( int and short ), the range must be at least 0 to 65535 , so that too must be at least 16 bits wide. Also, the standard mandates that the range of (unsigned) short is contained in the range of (unsigned) int , and the range of (unsigned) char must be contained in the range of (unsigned) short .
It is the smallest (16 bit) integer data type in C++. Some properties of the unsigned short int data type are: Being an unsigned data type, it can store only positive values. Takes a size of 16 bits.
As operands of -
and most other arithmetic operators, any values of integral type narrower than int
are promoted to int
.
So us1 - us2
behaves as (int)us1 - (int)us2
.
This rule is pretty annoying in modern C++, but it came in right from the earliest version of C (because int-sized registers were used for arithmetic) and it would break too much code to change it now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With