“There is no real difference between work and play – it's all living.”

-Richard Branson

Boolean Hacks in C

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

1
2
3
typedef unsigned char bool
const true = 1;
const false = 0;

Method 2: by Unknown

1
2
3
#define true 1
#define false 0
typedef unsigned char bool

Method 3: by Julian Assange in strobe.c v1.03

1
#define bool char

Method 4: by Julian Assange in strobe.c v1.05

1
2
3
#define bool int
#define FALSE 0
#define TRUE 1

Method 5: by Daniel Fredouille in C generic data structures

1
2
3
#define true (0==0)
#define false (!true)
typedef unsigned char bool

Method 6: by Qhull in libqhull.h

1
2
3
4
5
6
7
8
9
#define bool unsigned int
#ifdef False
#undef False
#endif
#ifdef True
#undef True
#endif
#define False 0
#define True 1

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