unsigned and int

can someone explain to me this snippet:

int i= -10;

unsigned u= 10;

std::cout << i + u << std::endl; // = 0 = -10 + 4,294,967,296 + 10 -4,294,967,296

Thank you in advance

Nir
Last edited on
Your output should be 0.

https://stackoverflow.com/questions/16728281/adding-unsigned-int-to-int

Wayne Uroda wrote:
When an unsigned int and an int are added together, the int is first converted to unsigned int before the addition takes place (and the result is also an unsigned int).


You can think of unsigned integers as being a long, finite ring of numbers that wraps around in a circle.
When you do i + u, first the -10 is converted to an unsigned int. Unsigned ints wrap back around after reaching their max number (in your case, 232 - 1), so 0 is equivalent to 232.

So, -10 gets converted into 232 - 10.

(-10) + 10 == (232 - 10) + 10 == 232 == 0 (mod 232)
Last edited on
Hi,
Thank you very much for your reply!
Still, I do not get where the last -4,294,967,296 came from?
As far as I can understand it should be: -10 + 10= 2^32 - 10 +10 = 2^32
Again, thanks any way
I don't know what you're referring to when you say -4,294,967,296. The only number your program prints is 0.

As far as I can understand it should be: -10 + 10= 2^32 - 10 +10 = 2^32
On your computer, an unsigned int happens to be 32-bit. This means the highest value it can store is 232-1. Once it reaches 232, it wraps back around to 0.

In modular arithmetic, this is saying: 0 == 232 (mod 232)
Last edited on
Your unsigned integer can represent values [0 .. 2^32) i.e. [0 .. 2^32-1]

The largest possible value is 2^32-1. There is no 2^32.

Lets do the same with two bits:
00 = 0
01 = 1
10 = 2
11 = 3

The largest value is 2^2-1 == 3. 3+1 is 11 + 01 in binary, which produces 100 (4). Alas, we keep only two bits, the 00. Therefore, 2^2 converts to 0 in our two-bit system.

2^32 converts to 0.


The -4,294,967,296 in comment ... no idea, who wrote that.
Topic archived. No new replies allowed.