Oleksiy
Oleksiy

Reputation: 39790

Can I always use 1-bit booleans?

In my opinion, one bit is all you ever need for a binary variable like bool. Is it in any way a bad decision to explicitly tell all bools to use only 1 bit?

struct Banana { 

    // little fields
    bool on_off : 1;
    bool yes_no : 1;
    bool left_right : 1;
    bool alive_dead : 1;
    bool in_out : 1;

};

Edit:

I know that it is not possible to take the address of a field. Any other downsides?

Upvotes: 4

Views: 270

Answers (3)

sh1
sh1

Reputation: 4731

I have encountered a couple of good compilers/architectures/functions where moving booleans into bitfields has drastically improved code quality and performance.

Unfortunately GCC is not one of those compilers (or was not last time I tested this).

When things go right, storing several booleans in a single register can relieve a lot of register pressure, consequently eliminating a lot of register spill to the stack and making the rest of the code much more efficient.

If the architecture has an adequate set of bit handling instructions then the test and manipulation operations can be as compact or more compact than comparable operations to extract booleans from whole registers or, worse, the stack.

Generally (even on x86), bit-packing booleans should result in more efficient code, but the limitation is the compiler.

Upvotes: 2

Tom Tanner
Tom Tanner

Reputation: 9354

There's a time/space/synchronisation trade off.

Clearly you can store 32 times as many bits in the same space.

However, to access an individual bool you need at least a masking operation, and probably a shift (though under certain circumstances, that is likely to be optimised out).

This has consequences if multiple threads of control attempt to modify booleans as you've changed a simple write for your update to a read/modify/write so now you have to add synchronisation.

Upvotes: 3

Mats Petersson
Mats Petersson

Reputation: 129314

If you have LOTS of these things, it saves space. But it does add at least an extra AND or OR instruction for each clear/set/check operation over the normal one-byte solution.

In the whole scheme of things, unless you actually have a HUGE number, there is probably no benefit.

Upvotes: 6

Related Questions