C doesn’t have a boolean datatype

Which can be a bit of a bummer, because I’ve been using loads of integer variables in a recent project which will only ever be 1 or 0.

Possibly bad practice, but I’ve also be using their values in calculations… and I wouldn’t know if that’s valid with booleans or not.

Phil Wilson 4th December 2006

If they’ll never change, maybe use an enum with TRUE = 0 and FALSE = 1 (or in whatever combination)?

Tom Gidden 12th December 2006

C does has something like a special case of boolean data type. Look into bit fields:

struct {
unsigned int foo:1;
unsigned int bar:1;
unsigned int baz:1;
unsigned int quux:1;
unsigned int bleh:1;
unsigned int meh:1;
unsigned int argh:1;
} flags;

This’ll give you a structure containing seven boolean flags. You can also do larger fields:

struct {
unsigned int foo:2;
unsigned int bar:2;
unsigned int bleh:2;
} twopairs;

That’ll give you three two-bit members, each of which can store 0, 1, 2 or 3.

Now, both of those structs *could* fit into a single byte, as each is less than 8 bits. However, due to word alignment and other peculiarities, you can’t really guarantee what size they’ll come out as, although it’s often in multiples of 4 bytes.

Try experimenting with sizeof() to see how they come out with different architectures and compilers. You also can’t guarantee (or even easily determine) what order the bits are stored either.

Anyway, bit fields can be very handy when you need to store a metric crapload of flags… for example, when storing a map for a game. Unfortunately, the code generated for bit fields can sometimes be pretty inefficient, and sometimes not as good as if you used bit masking (&&, ||,

Tom Gidden 12th December 2006

(hmmm… your comment system just cut me off when I typed two less-thans, and the rest of the comment is now lost forever.. *sniff*)

What I was going to say was that storing booleans in bits and bytes can be inefficient on modern architectures. While an ‘unsigned int’ is a waste of 31 bits (more or less) for a single boolean flag, a modern processor will probably deal with it faster than having to faff around with bits and bytes.

If you can be bothered, try out some different approaches to storing flags (bit fields, bitmasking, just using ints, chars, etc.) and then compile to assembly and see what happens.

It depends what your priorities are… memory, clarity, portability, flexibility, or speed. Bit fields do have the virtue of being clear yet space efficient, and this can be very handy if you’re trying to document or demonstrate an algorithm that still works well.

If you end up using bitmasks, it’s best to write macros where possible, rather than trying to show off your bool-fu inline.

Phil Wilson 15th December 2006

Worth noting that it’s easy to bugger up bit fields if you’re not paying enough attention ;)

Leave a Reply