简体   繁体   中英

When is int value ordinarily converted to unsigned?

Here is from C++ Prime 5th :

if we use both unsigned and int values in an arithmetic expression, the int value ordinarily is converted to unsigned.

And I tried the following code:

int i = -40;
unsigned u = 42;
unsigned i2 = i;
std::cout << i2 << std::endl; // 4294967256
std::cout << i + u << std::endl; // 2 

For i + u , if i is converted to unsigned , it shall be 4294967256 , and then i + u cannot equal to 2 .

Is int value always converted to unsigned if we use both unsigned and int values in an arithmetic expression?

Yes.

What you're experiencing is integer overflow . The sign of a negative number is given by the leading sign bit , which is either 0 (positive) or 1 (negative). However, for unsigned integers, this leading bit just gives you one more bit of integer precision, rather than an indication of sign. "Negative" signed numbers end up counting backwards from the maximum unsigned integer size.

How does this relate to your particular code? Well, -40 does get turned into 4294967256. However, 4294967256+42 can't fit in an unsigned integer, as if you remember -40 just turned into the max unsigned integer minus 39. So by adding 42, you exceed the capacity of your data-type. The would-be 33rd bit just gets chopped off, and you start over from 0. Hence, you still get 2 as an answer.

Signed:             -42,        -41, ...,         -1, 0, 1, 2
Unsigned:    4294967256, 4294967257, ..., 4294967295, 0, 1, 2, ...
                                                   ^--^ Overflow!

You'd probably be interested in reading about Two's Complement

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