简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM