简体   繁体   English

operator <<如果结果是unsigned int或unsigned short则解释算术运算

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

I use gcc 4.8.3 under fedora 19 64bits 我在fedora 19 64bits下使用gcc 4.8.3

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 结果: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 <<运算符似乎将第二个操作的结果解释为带符号的 short,而它将第一个操作的结果解释为unsigned int

As operands of - and most other arithmetic operators, any values of integral type narrower than int are promoted to int . 作为-和大多数其他算术运算符的操作数,任何比int窄的整数类型的值都被提升为int

So us1 - us2 behaves as (int)us1 - (int)us2 . 所以us1 - us2表现为(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. 这条规则在现代C ++中非常烦人,但它最早出现在C语言中(因为int大小的寄存器用于算术运算),它现在会破坏太多代码来改变它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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