About Me

My photo
By day I'm a propeller-head geek. I design software for electronic components for a major automotive supplier. When I'm not earning a paycheck, I enjoy playing music -- primarily jazz and classical but I dabble in other genres as well. I also compose, arrange, and play with electronic gadgets and toys. My other hobbies include photography, colored pencil drawing, genealogy, model railroading, and crosswords.

Wednesday, January 11, 2012

True and False in the C Programming Language

I know, C is dead, right? Not quite. While C has been supplanted in many industries by C++, C#, and other object-oriented languages, much of the automotive industry still relies on plain vanilla C - MISRA C, to be specific. I overheard the following question today: "should TRUE be set to !FALSE or should it be set to 1 - which is more MISRA compliant?" I don't know which is more MISRA compliant (off the top of my head), but I'd like to offer an alternative that, to my thinking, is more type-safe and avoids clashes with the macro definitions provided with many compilers.

Since C does not have native support for a Boolean type, it is common to #define TRUE and FALSE:

#define FALSE 0
#define TRUE !FALSE

FALSE is always zero and true may be any non-zero integer, so it is safest to let the pre-compiler decide what !FALSE means. This is portable but not type-safe; TRUE and FALSE may be compared to a result of any type (leaving the type conversion to the compiler). I like to use a typedef'd enumeration, instead:

typedef enum {eFALSE = 0; eTRUE;} BOOL_t;

Since this is "user defined", it is incompatible with the return type of standard library functions, so they must either be handled in the typical manner or with explicit casts.

Thinking about how to define and use boolean types in C reveals an important lesson about the "safe" use of C. That is: Avoid comparisons to TRUE (or eTRUE or whatever). Since zero will always be "false", comparisons with FALSE will always work.

No comments: