adding unsigned int to int

user2408639 picture user2408639 · May 24, 2013 · Viewed 15.8k times · Source
#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

Answer

Wayne Uroda picture Wayne Uroda · May 24, 2013

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