tags:

views:

340

answers:

2

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.

+9  A: 

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.

Jarin Udom
+13  A: 

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.

jn_
Ree
i guess this is an error in the book, because the text in the printf statement suggests that the author wanted to show the properties of an unsigned int, which in fact he doesn't.
jn_
Jack