I switched to fixed-length integer types in my projects mainly because they help me think about integer sizes more clearly when using them. Including them via #include <inttypes.h>
also includes a bunch of other macros like the printing macros PRIu32
, PRIu64
,...
To assign a constant value to a fixed length variable I can use macros like UINT32_C()
and INT32_C()
. I started using them whenever I assigned a constant value.
This leads to code similar to this:
uint64_t i;
for (i = UINT64_C(0); i < UINT64_C(10); i++) { ... }
Now I saw several examples which did not care about that. One is the stdbool.h
include file:
#define bool _Bool
#define false 0
#define true 1
bool
has a size of 1 byte on my machine, so it does not look like an int
. But 0
and 1
should be integers which should be turned automatically into the right type by the compiler. If I would use that in my example the code would be much easier to read:
uint64_t i;
for (i = 0; i < 10; i++) { ... }
So when should I use the fixed length constant macros like UINT32_C()
and when should I leave that work to the compiler(I'm using GCC)? What if I would write code in MISRA C?
int
is narrower than 32 bits. – Solfatara