Velocity Reviews > unsigned variables

# unsigned variables

Christian Christmann
Guest
Posts: n/a

 05-07-2006
Hi,

what does the ANSI C-99 standard says when an unsigned variable
is assigned a negative number?, i.e.

unsigned char a = -100;

Is this undefined behavior or should the negative number be casted
to a unsigned value?

Thank you.

Chris

Walter Roberson
Guest
Posts: n/a

 05-07-2006
In article <445e2e51\$0\$4494\$(E-Mail Removed)-online.net>,
Christian Christmann <(E-Mail Removed)> wrote:
>what does the ANSI C-99 standard says when an unsigned variable
>is assigned a negative number?, i.e.

>unsigned char a = -100;

>Is this undefined behavior or should the negative number be casted
>to a unsigned value?

The behaviour is well defined: (UCHAR_MAX+1) will be added to
the negative quantity sufficient times to arrive at a positive
quantity.

In 2's complement arithmetic, the end result is the same bit
pattern for signed char a = -100 and unsigned char a = -100,
but the standard is written the way it is so as not to assume
2's complement.
--
There are some ideas so wrong that only a very intelligent person
could believe in them. -- George Orwell

Michael Mair
Guest
Posts: n/a

 05-07-2006
Christian Christmann schrieb:
> Hi,
>
> what does the ANSI C-99 standard says when an unsigned variable
> is assigned a negative number?, i.e.
>
> unsigned char a = -100;

The conversion "integer->unsigned integer" is done adding or subtracting
the unsigned integer's maximal representable value plus one sufficiently
often to arrive in the range of the unsigned integer type.
In this case, this will effectively amount to
unsigned char a = (UCHAR_MAX + 1) - 100;

> Is this undefined behavior

No.
The conversions "floating point->signed or unsigned integer" or
"floating point->floating point" lead to UB if the value cannot be
represented in the target type.
I.e.
unsigned char a = -100.0;
is not necessarily the same as the integer version.
A safe version of this conversion is
int b = -100.0; /* convert to integer type which can represent
** the value */
unsigned char a = b;

> or should the negative number be casted to a unsigned value?

A cast is an explicit conversion. The result is the same as for
an implicit conversion, i.e.
unsigned char a = (unsigned char) -100;
leads to the same result as
unsigned char a = -100;
Note: Sometimes, casts are used to "shut up the compiler" in
situations like this; this is not necessarily a good idea.

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.