Unsigned Char Vs Char

topic under construction

!!! Contains invalid information !!!

Ugly programming error

Wrong

unsigned char input[1];
scanf("%1c", input);
printf("%d",  atoi(input));

WRONG RESULT: atoi(input); => -822413695 (win) => -1 (linux)

Correct

char input[1];
scanf("%1c", input);
printf("%d",  atoi(input));

Correct Result: atoi(input); => 1

Unsigned char vs. char

The types char, signed char, and unsigned char are always
distinct, even though they have the same number of bits,
and type char has the same representation and behavior
as either signed char or unsigned char. By analogy, it
is common for types int and long to have the same
representation, although they are always distinct types.
If you want a small unsigned integer object capable of
representing unsigned values in the range 0-255, use unsigned
char. Type "plain" char need not behave as an unsigned type.

If you use the value of these integers in expressions, you
must understand the rules for mixed-mode arithmetic. When
some of the operands in an expression are signed and some
are unsigned, you have to pay close attention to the rules
to get the results you want. Such code tends to be fragile.

Consider whether a signed short or int would be better
overall than an unsigned char. (A signed short must also
be capable of representing values in the range 0-255).

OTOH, if you are using bitwise operations on the values, e.g.
shifting and masking, you probably do want an unsigned
type. The rules of arithmetic and bit operations on unsigned
types are completely defined. Some aspects of arithmetic and
bit operations on signed types depend on the implementation.

If you want to store characters (as opposed to small positive
integers), use "plain" char. That type will have the correct
behavior for all character-oriented classes and functions,
whereas type unsigned char (or signed char) will not always work.

If you want to do arithmetic on characters, you don't have
many really good choices. You should ordinarily use type
"plain" char
, but since it can behave as either a signed
or unsigned value, some operations might not behave as you
want unless you use casts or assigment to "larger" integer
types to force specific behavior.

But some arithmetic operations are completely defined for
type char. For example, all the 96 characters in the basic
character set must have a non-negative representation, even
if type char is signed. The values of the integer characters
'0' through '9' must be contiguous in ascending order,
meaning '1'+2 always has the same value as '3'.

http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/fd763fd97d08ac15/0ba49297a6ad8d1d?hl=en&lnk=st&q=%22unsigned+char%22+vs.+%22char%22#0ba49297a6ad8d1d

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License