What is the advantage of using uint8_t
over unsigned char
in C?
I know that on almost every system uint8_t
is just a typedef for unsigned char
, so why use it?
uint8_t always matches range and size of unsigned char and padding (none) when unsigned char is 8-bit. When unsigned char is not 8-bit, uint8_t does not exist.
If it exists, uint8_t must always have the same width as unsigned char . However, it need not be the same type; it may be a distinct extended integer type. It also need not have the same representation as unsigned char ; for instance, the bits could be interpreted in the opposite order.
If the intended use of the variable is to hold an unsigned numerical value, use uint8_t; If the intended use of the variable is to hold a signed numerical value, use int8_t; If the intended use of the variable is to hold a printable character, use char.
2.2. A UINT8 is an 8-bit unsigned integer (range: 0 through 255 decimal).
It documents your intent - you will be storing small numbers, rather than a character.
Also it looks nicer if you're using other typedefs such as uint16_t
or int32_t
.
Just to be pedantic, some systems may not have an 8 bit type. According to Wikipedia:
An implementation is required to define exact-width integer types for N = 8, 16, 32, or 64 if and only if it has any type that meets the requirements. It is not required to define them for any other N, even if it supports the appropriate types.
So uint8_t
isn't guaranteed to exist, though it will for all platforms where 8 bits = 1 byte. Some embedded platforms may be different, but that's getting very rare. Some systems may define char
types to be 16 bits, in which case there probably won't be an 8-bit type of any kind.
Other than that (minor) issue, @Mark Ransom's answer is the best in my opinion. Use the one that most clearly shows what you're using the data for.
Also, I'm assuming you meant uint8_t
(the standard typedef from C99 provided in the stdint.h
header) rather than uint_8
(not part of any standard).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With