One of the weaknesses of the C language when measured against the newer, trendier programming languages is that it lacks a Boolean type. That is, a variable that’s either one or zero. This issue was addressed with the C99 standard and its addition of the underscore _Bool data type. It’s furthered in the C23 standard with the (better) bool type as well as the true and false keywords available in just about every other programming language used today. It’s time for a deep dive into the binary pool of bool.
Yes, I know that the C99 standard was sincere with its addition of the underscore keywords: _Bool, _Complex, and _Imaginary. Adding the initial underscore seems like an insult to me. Requiring the initial capital letter adds injury to the insult. Further: _Bool is deprecated with the C23 standard. So much for that.
Despite the apparent desperation, the stdbool.h header file is available. This resource is what C programmers lean on when they desire to fill the void left in C by missing binary/Boolean capabilities. It’s such a useful header file, that many coders add it along with stdio.h and stdlib.h by default.
The stdbool.h header carries three burdens:
- It defines bool as a data type
- It defines the true constant
- It defines the false constant
The header file also contains a defined constant _bool_true_false_are_defined, which is set to 1. This constant is used as a test to ensure that the header file is included and that your code can use bool, true, and false without messing up anything. I don’t know how a C23 compiler deals with this header file as it has its own keywords for bool, true, and false.
In the stdbool.h header file, the bool data type is tied to _Bool. It’s defined, not typedef‘d:
#define bool _Bool
Here are the definitions for true and false:
#define true 1
#define false 0
Since I first learned C, my habit was to define these constants myself, traditionally in uppercase:
#define TRUE 1
#define FLASE 0
I still default to this definition in my code. But occasionally I use these definitions, which was taught to me by a C guru back in the 1980s:
#define FALSE 0
#define TRUE !FALSE
I’m rather fond of this method.
All this stuff goes away once your compiler adopts the C23 standard. Until then, these are your options should you elect to include the stdbool.h header file. Then you can freely play with Boolean values, which I am eager to show you in next week’s Lesson.