Boolean Hacks in C

27 September 2010

You’re used to Booleans as logical or truth values but you miss them in C. You’d like your code to be more verbose and readable instead of 1’s and 0’s all over the place.

Here are some simple workarounds I’ve found over the years. Most of these take advantage of chars being an integral data type in 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

Do you know of any others? Send them to me and I’ll post them here!

This content is open source.
Please help improve it.