Is there any difference between using char
(plain char) or signed/unsigned char
to store characters in C?
Yes, yet ...
Use of >>, *, /, %
creates differences when the character object is some signed character and negative vs. the unsigned character same bit-pattern positive.
Assignment to int
can have an unexpected sign extension with negative characters.
is...()
invokes undefined behavior (UB) when the character argument is negative (and not EOF
).
The cases for _Generic
distinguish between char
, signed char
, unsigned char
.
Pedantic: With archaic non-2's complement using signed characters, user code often does not properly distinguish between +0 and -0 for the null character.
Signed types have more implementation defined behaviors than unsigned types when converting to other types, thus reducing portability.
"signed char are at a disadvantage with respect to working with UTF-8 encoded text".
... Other issues too.
... not always
str...()
behave as if the character was unsigned char
regardless if char
is signed or unsigned. This is important in some functions, like strcmp()
as when the difference in a string involves a negative char
.
"%c", "%s"
in *scanf(), *printf()
matches all 3 types (or pointers to them).
There are no padding bits with the 3 character types and they consume the same space, although the soon to be dropped non-2's complement encodings allow for a trap representation for signed character types.
... can i use char
or signed char
or unsigned char
to store characters?
Yes.
The string manipulation, char
has the advantage in matching str..()
function signatures.
For logic and raw byte code, use unsigned char
.
Use signed char
when small signed values are needed.
@Steve Summit, @Support Ukraine
If the answer is "No you cant", my next question will be, why? can you explain me the reason for use strictly char (plain char) to store characters?
N/A