Re: Unsigned int

From: Martin Dickopp (expires-2003-12-31_at_zero-based.org)
Date: 11/20/03


Date: 20 Nov 2003 09:43:38 +0100


"Vijay Kumar R Zanvar" <vijoeyz@hotpop.com> writes:

> "Vijay Kumar R Zanvar" <vijaykumar.rz@globaledgesoft.com> wrote in message
> news:bphjth$1n93ru$1@ID-203837.news.uni-berlin.de...
> > 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.

Good! But the sections you quoted don't apply here.

> 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:
> [...]

The representation is irrelevant here. 6.2.6.1#4 defines what `representation
of a value' means:

    Values stored in non-bit-field objects of any other object type consist
    of n × CHAR_BIT bits, where n is the size of an object of that type, in
    bytes. The value may be copied into an object of type unsigned char [n]
    (e.g., by memcpy); the resulting set of bytes is called the object
    representation of the value. [...]

You really want 6.3.1.3#2, which describes how an integer value is converted
to an unsigned integer:

   Otherwise, if the new type is unsigned, the value is converted by
   repeatedly adding or subtracting one more than the maximum value that
   can be represented in the new type until the value is in the range of
   the new type.49)
   ----
   Footnote:
   49) The rules describe arithmetic on the mathematical value, not the
       value of a given type of expression.

In other words, the value is reduced modulo the maximum value plus one, so
that -1 becomes the maximum value.

Martin