Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 985
MTVS Avatar asked Oct 20 '25 16:10

MTVS


1 Answers

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

like image 102
Pubby Avatar answered Oct 22 '25 07:10

Pubby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!