In C/C++, what an unsigned char
is used for? How is it different from a regular char
?
This is implementation dependent, as the C standard does NOT define the signed-ness of char
. Depending on the platform, char may be signed
or unsigned
, so you need to explicitly ask for signed char
or unsigned char
if your implementation depends on it. Just use char
if you intend to represent characters from strings, as this will match what your platform puts in the string.
The difference between signed char
and unsigned char
is as you'd expect. On most platforms, signed char
will be an 8-bit two's complement number ranging from -128
to 127
, and unsigned char
will be an 8-bit unsigned integer (0
to 255
). Note the standard does NOT require that char
types have 8 bits, only that sizeof(char)
return 1
. You can get at the number of bits in a char with CHAR_BIT
in limits.h
. There are few if any platforms today where this will be something other than 8
, though.
There is a nice summary of this issue here.
As others have mentioned since I posted this, you're better off using int8_t
and uint8_t
if you really want to represent small integers.