Question

#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

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top