Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator << interprets arithmetic operation if the result is unsigned int or unsigned short

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

like image 601
axel Avatar asked Aug 21 '14 12:08

axel


People also ask

Is unsigned an int or short?

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 .

What is unsigned short int?

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.


1 Answers

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.

like image 124
M.M Avatar answered Sep 21 '22 02:09

M.M