Search code examples
c++typesunsignedsigned

signed to unsigned casting


look at this code:

void main ()
{
int i = -1;
unsigned u = 1;

cout << u + i;
}

the addition of the u (unsigned) and i (signed), so i must be converted to the unsigned type, so it should be interpreted ( (2 ^ 32) - 1 ) and the expression should change from: -1 + 1 to ( (2 ^ 32) - 1 ) + 1 but when i run the code it results to 0 why?


Solution

  • -1 in an unsigned representation of the largest possible number unsigned can hold (UINT_MAX).

    Adding 1 to this wraps over due to the properties of unsigned, thus equaling 0.