Home > database >  Is there any difference between using char (plain char) or signed/unsigned char to store characters
Is there any difference between using char (plain char) or signed/unsigned char to store characters

Time:12-12

i have a question, i have read some post here in SO that ask for help about when using char, when using signed char or unsigned char; in that posts, they answered that for store characters we must use char and for using small data use signed/unsigned char, but, for what i know, char is implementation defined, so it can be equal to signed char or unsigned char.

The question is, can i use char or signed char or unsigned char to store characters? 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?

Thanks in advance!!

CodePudding user response:

It's implementation defined if char is signed or unsigned as you said.

If you need a particular version specify it. ASCII is 7 bits so for that it doesn't matter. If you need 8 bit or more (like UTF-8) it depends on how you use the data. For example left shift is well defined for unsigned values, but implementation defined if the left operand is negative. if(ch < 0) is a no-op for unsigned but may matter greatly for signed.

In the upcoming C 2023 standard the new type char8_t may be of interest to you. It is unsigned and the same as unsigned char.

CodePudding user response:

Is there any difference between using char (plain char) or signed/unsigned char to store characters in C?

Yes.

Use of >>, *, /, % creates differences when the character object is signed or unsigned.

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, code does not properly distinguish between 0 and -0 for the null character.

Not always.

str...() behave as if the character was unsigned char. This is important in some functions, like strcmp() and the difference in a string involves a negative character.

There are no padding bits with the 3 character types, although the soon to be dropped non-2's complement encodings allow for a trap pattern.


... can i use char or signed char or unsigned char to store characters?

Yes.


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

CodePudding user response:

Yes you can store characters with char.

char is only one Byte long so -128 to 127

unsigned char is the same but 0 to 255

see more here : https://en.wikipedia.org/wiki/C_data_types

  • Related