Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I always use 1-bit booleans?

Tags:

c++

boolean

bit

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?

like image 553
Oleksiy Avatar asked Dec 21 '22 01:12

Oleksiy


2 Answers

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.

like image 194
Mats Petersson Avatar answered Jan 05 '23 10:01

Mats Petersson


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.

like image 20
Tom Tanner Avatar answered Jan 05 '23 08:01

Tom Tanner