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