Vijay Kumar R Zanvar said:
Have a look at the follwing program....
main()
{
unsigned int i = -1;
printf("%u\n", i);
}
Why it prints some big number?
Hi,
I am answering myself!
Probably, I knew the answer. Now
its time to see if I am correct or not! Suggestions welcome.
....
Luckily, these days I am reading the ISO/IEC 9899:1999, the current
C Standard. I will give the answer according to how I understand the
question, and the Standard:
* For unsigned integers, other than unsigned char, the bits of
object representation are divided into two groups:
+ Value bits, and
+ Padding bits
If there are N value bits, then the range of unsigned integer
is 0 to 2^N - 1.
* For signed integers, the bits of the object representation are
divided in the three groups:
+ Value bits
+ Padding bits
+ Sign bit (exactly one bit)
If the sign bit is 0, the object representation of the signed
integer is equal to that of unsigned integer.
Object representation is simply the bit pattern that appears in
the memory of any object, say, int or float or struct.
There is another term used regarding integers: precision.
Precision of an integer type is the number of bits used to
represent a value, except padding and sign bits.
Ex: Precision of
5 is 3 (because 3 bits are needed, i.e., 101)
-1 is 32 (if sizeof (int) == 4 )
The value of padding bits are unspecified as they do not affect
the final result.
With this knowledge, let us see how the following:
unsigned int i = -1;
is represented
See section A6.5 of K&R. It says:
... Otherwise, if either operand is unsigned int, the other
is converted to unsigned int. ...
So, -1 is converted into unsigned integer, which has no sign bit!
-1 is represented in 2's compliment, which is 0xffffffff. If you
store this value in an unsigned type, it is a big value minus sign.
I think, from here onwards you can derive what I mean!
Thanks.