I just started working on a big project which is supposed to be platform independent, but it actually uses types which are implementation defined such as char
.
This had already caused some problems, since for some devices char
is by default signed
while for others unsigned
.
I would like to find a solution in order to avoid the use of implementation defined types in code that must be platform independent.
unsigned char
(or signed char
), using compiler parameters (ex: -funsigned-char), typedef
s, or others?In theory, the answer is very simple:
Always use types for the purpose they are intended for. E.g. you want implementation-defined types for something like the size of an array because on different platforms, the upper bound of such a size will be different. Similar for pointers. For the need of fixed-size types, C already provides appropriate typedef
s in stdint.h
.
Here's an incomplete "what-to-use" list:
unsigned
) int
for any integer that doesn't need to have a fixed size and will never exceed the range of 16 bitschar
for characters, int
and casts to unsigned char
when dealing with library functions that store characters in an int
.size_t
for anything related to the size of objects, e.g. array indicesuintptr_t
whenever you need to store the value of a pointer in an integerintX_t
/uintX_t
(with X
being the number of bits) for any integer where you need a fixed number of bits that shouldn't change depending on the target platform.int_leastX_t
/uint_leastX_t
instead. An implementation that can't address an octet wouldn't provide e.g. uint8_t
, but it would provide uint_least8_t
with more bits.