Blog‎ > ‎

Boolean Hack in C

posted 27 Sep 2010 21:21 by Dennis Ideler   [ updated 7 Mar 2012 21:12 ]
Problem: You're used to Booleans as logical/truth values but you miss them in C. You'd like your code to be more verbose instead of 1's and 0's all over the place.

Here are some simple workarounds that I've observed over the years. Most of these take advantage of chars being an integral data type in C/C++ (i.e. they are stored as integers).
Method 1: by unknown
typedef unsigned char bool
const true = 1;
const false = 0;
Method 2: by unknown
#define true 1
#define false 0
typedef unsigned char bool
Method 3: by Julian Assange in strobe.c v1.03
#define bool char
Method 4: by Julian Assange in strobe.c v1.05
#define bool int
#define FALSE 0
#define TRUE 1
Method 5: by Daniel Fredouille in C generic data structures
#define true (0==0)
#define false (!true)
typedef unsigned char bool
Method 6: by Qhull in libqhull.h
#define bool unsigned int
#ifdef False
#undef False
#ifdef True
#undef True
#define False 0
#define True 1