MTVS
MTVS

Reputation: 2096

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?

Upvotes: 4

Views: 213

Answers (2)

jwismar
jwismar

Reputation: 12258

(unsigned) -1 is 0xFFFFFFFF. 1 + 0xFFFFFFFF = 0x100000000 which overflows the int, and results in 0.

Upvotes: 1

Pubby
Pubby

Reputation: 53017

-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.

Upvotes: 6

Related Questions