unsigned variables

  • Thread starter Christian Christmann
  • Start date
C

Christian Christmann

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
 
W

Walter Roberson

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.
 
M

Michael Mair

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top