I am reviewing coding guidelines for C and we still have the guideline to typedef uint8_t
for booleans. I work for a company in the automotive industry, therefore doing embedded software and usually working with Renesas micro-processors alongside GreenHills compilers.
I think that since C99 has been out there for so many years, the type definition is redundant and I would expect all compilers for modern platforms to support _Bool
. So, is it still worth having the typedef
?
Bonus question: I am trying to put together some guidelines for C++. I have a relatively limited background using C++, but again my opinion is that a typedef
for bool
should not be at all beneficial. Should we use the fundamental C++ bool
type or is there any reason why we should use a custom typedef
ed T_BOOL instead?
It is simple:
bool
from stdbool.h. _Bool
is also fine. Ugly typedefs are not ok and bad practice.Assuming C90:
There is absolutely no harm in using an 8 bit type for the boolean typedef. An 8 bit type will save a little bit of RAM. It can be done like this:
typedef uint8_t BOOL;
#define FALSE 0u
#define TRUE 1u
The most common form is however probably a typedef enum { FALSE, TRUE } BOOL;
.
Never use all lower case! Since bool
, false
and true
will collide with the standard if you port to a standard C compiler.
All of these home-brewed forms are bad practice and an obsolete way of writing C. There are no excuses left for sticking with dangerous C90, particularly not in automotive systems that tend to be safety-critical.
As for MISRA-C:2012, it simply states that you should have some sort of boolean type. It maintains backwards compatibility with C90 and therefore doesn't enforce bool
. It has lots of rules for how to treat boolean types however, and prevents using them together with various forms of arithmetic.
For compatibility with C++ you should definitely use standard C bool
. That type was explicitly designed with C++ compatibility in mind.