Christian said:
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