I'm reading the second edition of K&R book and one of the exercises requires printing all maximum integer values defined in limits.h header. However, this...
printf("unsigned int: 0 to %d\n", UINT_MAX);
... outputs the following:
unsigned int: 0 to -1
How come I get -1? Anyone could explain this behaviour?
I'm using Digital Mars C compiler on Vista.
This is because UINT_MAX resolves to -1 if treated as a signed integer. The reason for this is, that integers are represented in two's-complement. As a consequence, -1 and 4294967296 (i.e. UINT_MAX) have the same bit representation (0xFFFFFFFF, i.e. all bits set) and that's why you get a -1 here.
Update:
If you use "%u" as the format string you will get the expected result.
In the printf, I believe %d is a signed decimal integer, try %u instead.
The max value of an unsigned int has the most significant bit set (it is all 1s). With a signed int, the most significant bit specifies negative numbers, so when you're printing an unsigned int as a signed int, printf thinks it is negative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With