Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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.

like image 770
Ree Avatar asked Nov 29 '22 12:11

Ree


2 Answers

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.

like image 143
newgre Avatar answered Dec 16 '22 07:12

newgre


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.

like image 43
Jarin Udom Avatar answered Dec 16 '22 07:12

Jarin Udom