CodeSOD: True Enough

Managing true and false values is historically challenging. In the world of C, there's even a history to those challenges. Prior to the C99 standard, there wasn't a standardized version of boolean values, but there was a convention which most applications followed, based on how C conditionals and boolean logic works.

In C, anything non-zero is considered "true". So, if(0) { … } won't execute the branch, but if(99) { … } will. As a result, when people wanted to make boolean equivalents, they'd use the C preprocessors to specify something like:

#define TRUE 1 #define FALSE 0

This is, with some caveats, essentially what stdbool.h added in C99. There's no reason why TRUE needs to specifically be 1, as long as it's anything but zero. That's basically the only goal, as long as TRUE is anything but zero, if(TRUE) will behave as expected. I cannot stress enough that the only way to mess this up is to make TRUE zero. If there's one rule about defining your own boolean constants in C/C++ don't make TRUE zero.

Anyway, let me turn this over to Charles C:

I worked at a small-medium company that did a lot of subcontracted development work for a wide variety of clients. Every C or C++ project had to include the company's "standard" header field, which was to be included in every code file.
Buried halfway down this 300+-line file was this:

#define TRUE 0 #define FALSE 1

So, if (TRUE) {…} in this would not execute the branch. If you were using these constants, you'd need patterns like if (variable==TRUE) which is definitely an anti-pattern that hurts readability and frankly just annoys me. But at its core, this is just a hidden landmine in the code base, which is going to confuse anyone who isn't deeply entrenched in this code, and create huge piles of unnecessary errors.

[Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published. Required fields are marked *