简体   繁体   中英

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

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 (ie UINT_MAX) have the same bit representation (0xFFFFFFFF, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM