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?
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?
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.
As you said, "almost every system".
Char is probably one of the less likely to change, but once you start using uin16_t and friends, using uin8_t blends better, and may even be part of a coding standard.
On almost every system I've met uint8_t == unsigned char, but this is not guaranteed by the C standard. If you are trying to write portable code and it matters exactly what size the memory is, use uint8_t. Otherwise use unsigned char.
Just to be pendantic, 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[2], 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).
There's little. From portability viewpoint, char
cannot be smaller than 8 bits, and nothing can be smaller than char
, so if a given C implementation has an unsigned 8-bit integer type, it's going to be char
. Alternatively, it may not have one at all, at which point any typedef
tricks are moot.
It could be used to better document your code in a sense that it's clear that you require 8-bit bytes there and nothing else. But in practice it's a reasonable expectation virtually anywhere already (there are DSP platforms on which it's not true, but chances of your code running there is slim, and you could just as well error out using a static assert at the top of your program on such a platform).
The whole point is to write implementation-independent code. unsigned char
is not guaranteed to be a 8-bit type. uint8_t
is.
That is really important for example when you are writing a network analyzer. packet headers are defined by the protocol specification, not by the way a particular platform's C compiler works.