in Programming in C
1,701 views
0 votes
0 votes

I went through this article but couldn't get one point where it says that 

"It only makes a difference if the integer is negative (for signed inputs) or between INT_MAX+1 and UINT_MAX (e.g. between 231 and 232-1). In that case, if you use the %d specifier, you'll get a negative number, whereas if you use %u, you'll get a large positive number."

I am not getting how can an address value be negative ?

http://stackoverflow.com/questions/5208641/difference-between-printing-a-memory-address-using-u-and-d-in-c

in Programming in C
1.7k views

2 Answers

0 votes
0 votes
let storage class is 32 bit..

signed integer means %d. Range of signed interger is (-2^31-1 to 2^31-1).

Range of unsigned integer is (0 to 2^32-1) .

compare both ranges. let In signed integer space used to store negative no i.e. (-2^31-1 to 0) is X. now der are no negative no in Unsigned integer. so this X used to store those no's which are greater than (2^31-1) i.e. X contains (2^31 to 2^32-1).
0 votes
0 votes

I'm explaining assuming int is of size 4, but only the minimum size of 2 is guaranteed by C standard. Still, in all real C compilers, 4 is the default now. 

With 4 bytes we have 32 bits for int. Now, if we have only unsigned integers, this corresponds to $0 - 2^32 -1$. 

Number Signed Unsigned
0x7fff ffff  2^31 - 1 2^31-1
0x ffff ffff -1 or depends on the negative representation used 2^32 - 1

As shown in the above table as long as the most significant bit is 0, the number is positive and signed and unsigned representation is the same. When we use "%d", the parameter is assumed to be in "signed representation" and when we give "%u", the parameter is assumed to be in "unsigned representation". Since both representations are same as long as the most significant bit is 0, we are safe to use both format specifiers for these range of values. But depending on the type being passed to print, compiler might produce warnings. 

NB: Format specifiers never do any type conversion. They simply assume the parameter as whichever type the format tells. So, giving "%d" and passing a float value or vice versa produces unexpected result and not the int value of the float. 

by

Related questions