I'm using mplabX 4.20, and xc8 compiler. I'm trying to understand
which is the difference between uint8_t and unsigned char. Both of
them have size from 0 till 255. Both of can hold characters and
numbers. But which is better to use, and for which case?
unsigned char
is the unsigned integer type corresponding to signed char
. Its representation does not use any padding bits. Both of these occupy the same amount of storage as type char
, which is at least 8 bits, but may be more. The macro CHAR_BIT
tells you how many it comprises in your implementation. Every conforming C implementation provides all of these types.
uint8_t
, if available, is an unsigned integer data type exactly 8 bits wide and with no padding bits. On an implementation having CHAR_BIT
defined as 8, this is the same type as unsigned char
. On such systems you may use the two types interchangeably wherever the declarations provided by stdint.h
are in scope. On other systems, uint8_t
will not be declared at all.
Example if i want to create a buffer for holding a string.
If you want to declare a buffer for holding a string then as a matter of style, you should use type char
, not either of the other two:
char buffer[20] = "Hello World";
Although either of the other two, or signed char
, can also be used for string data (provided in the case of uint8_t
that the type is defined at all), type char
is the conventional one to use for character data. Witness, for example, that that's the type in terms of which all the string.h
functions are declared.
You should use uint8_t
where and only where you need an integer type with exactly its properties: unsigned, 8 value bits, no padding bits.
You should use unsigned char
where you want the smallest unsigned integer type available, but you don't care whether it is exactly 8 bits wide, or where you want to emphasize that it is the same size as a char
-- the smallest discrete unit of storage available.
You should use signed char
where you want the smallest signed integer type available but don't care about the exact size or representation.
You should use int8_t
where you want a signed integer type with exactly 7 value bits, one sign bit, and no padding bits, expressed in two's complement representation.
You should remain mindful that uint8_t
and int8_t
are not guaranteed to be available from every C implementation, and that where they are available, their use requires inclusion of stdint.h
. Furthermore, this header and these types were not part of C90 at all, so you should not use them if compatibility with legacy C implementations is important to you.