axel
axel

Reputation: 91

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

Upvotes: 6

Views: 134

Answers (1)

M.M
M.M

Reputation: 141628

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.

Upvotes: 5

Related Questions