adding unsigned int to int [duplicate]
Asked Answered
H

2

7
#include <iostream>
int main ()
{
    using namespace std;
    unsigned int i = 4;
    int a = -40;
    cout<<a+i<<endl;
    return 0;
}

Executing this gives me 4294967260

I know there's a conversion taking place, from a signed int to unsigned int, but how and why this particular value? I noticed it's close to the sum of | 2147483647 | + 2147483647

Hashim answered 24/5, 2013 at 5:36 Comment(1)
Check this one too.Mendelson
B
17

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).

-1, while being the first negative number, is actually equivalent to the largest unsigned number - that is, (unsigned int) -1 === UINT_MAX.

-2 in unsigned form is UINT_MAX - 1, and so on, so -40 === UINT_MAX - 39 === 4294967256 (when using 32bit ints).

Of course, adding 4 then gives your answer: 4294967256 + 4 = 4294967260.

This is a great quiz where you can learn some of the rules of integers in C (and similarly C++): http://blog.regehr.org/archives/721

Bellflower answered 24/5, 2013 at 5:45 Comment(3)
Correct. An alternative to this is to turn the 4 into an int and then add them, then if you want an unsigned int do an if block that if the result is >= 0 then it is converted to an unsigned int.Zebec
Why does the int is converted to unsigned and not the way around?Hampson
For two's complement you end up with the same bit pattern -- the context of the result (which evidently is unsigned by default) determines whether the result is signed or unsigned.Holotype
J
1

Represent i and a in hexadecimal:

i =   4: 0x 0000 0004
a = -40: 0x FFFF FFD8  

Following the implicit conversion rules of C++, a in a + i will be cast to unsigned int, that is, 4294967256. So a + i = 4294967260

Jade answered 24/5, 2013 at 5:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.