Why does printf () print -1 for large integers?

I am reading the second edition of K & R, and one exercise requires printing all the maximum integer values ​​defined in the limits.h header. However, this ...

printf("unsigned int: 0 to %d\n", UINT_MAX); 

... outputs the following:

 unsigned int: 0 to -1 

Why am I getting -1? Can anyone explain this behavior?

I am using the Digital Mars C compiler on Vista.

+4
source share
2 answers

This is because UINT_MAX allows -1 if it is treated as a signed integer. The reason for this is that integers are represented in two's-complement . As a result, -1 and 4294967296 (i.e. UINT_MAX) have the same bit representation (0xFFFFFFFF, i.e. All set bits), and therefore you get -1 here.

Update:
If you use "% u" as the format string, you will get the expected result.

+15
source

In printf, I believe that% d is a signed decimal integer, try% u instead.

The highest unsigned int value has the most significant bit (these are all 1s). With a signed int, the most significant bit indicates negative numbers, so when you print an unsigned int as a signed int, printf is negative.

+9
source

All Articles