adding unsigned int to int

17,119

Solution 1

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

Solution 2

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

Share:
17,119
Admin
Author by

Admin

Updated on June 14, 2022

Comments

  • Admin
    Admin almost 2 years
    #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

  • Sellorio
    Sellorio almost 11 years
    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.
  • almanegra
    almanegra over 8 years
    Why does the int is converted to unsigned and not the way around?
  • wcochran
    wcochran over 5 years
    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.