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

I am using gcc 4.8.3 in Fedora 19 64 bit

 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 statement seems to interpret the result of the second operation as a signed short whereas it interprets the result of the first operation as unsigned int
+6
source share
1 answer

As operands - and most other arithmetic operators, any values โ€‹โ€‹of an integral type that are narrower than int are promoted to int .

So, us1 - us2 behaves like (int)us1 - (int)us2 .

This rule is quite annoying in modern C ++, but it came from the earliest version of C (because arithmetic used registers with sizes), and now it can break too much code.

+5
source

Source: https://habr.com/ru/post/974154/


All Articles