I'm starting to program in C and I'm having a problem to understand some results I'm getting. I'll paste the code here:
#include <stdio.h>
unsigned int main(void)
{
unsigned int x = 0;
printf("%u\n",x-1);
return 0;
}
The terminal is returning 4.294.967.295, and I'm not getting why. I know that this value is the max value of a unsigned int
, but actually I was expecting some warning from the compiler that I would have to use a int
type not an unsigned int
because the result is negative. Anyway, can someone help me?
When you use an unsigned type all of the bits are used to represent non-negative values ( i.e., >= 0). Think of this as the values wrapping around, so when you decrement below the lower limit (0), you wrap around to the largest value (with 32 bits, 2^32 - 1).
Also, note you did not assign a negative value to variable x
, you just provided an expression that subtracted 1 from it. I.e.,
x-1
vs
x = x - 1;
though whether you would have gotten a warning about this would probably depend on the compiler and the warning levels set.