DevNoteHQ
DevNoteHQ

Reputation: 303

C++: Is bool a 1-bit variable?

I was wondering if bools in C++ are actually 1-bit variables. I am working on a PMM for my kernel and using (maybe multidimensional) bool-arrays would be quiet nice. But i don't want to waste space if a bool in C++ is 8 bit long...

EDIT: Is a bool[8] then 1 Byte long? Or 8 Bytes? Could i maybe declare something like bool bByte[8] __attribute__((packed)); when using gcc? And as i said: I am coding a kernel. So i can't include the standard librarys.

Upvotes: 8

Views: 11094

Answers (3)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

No there's no such thing like a 1 bit variable.

The smallest unit that can be addressed in c++ is a unsigned char.

Is a bool[8] then 1 Byte long?

No.

Or 8 Bytes?

Not necessarily. Depends on the target machines number of bits taken for a unsigned char.


But i don't want to waste space if a bool in C++ is 8 bit long...

You can avoid wasting space when dealing with bits using std::bitset, or boost::dynamic_bitset if you need a dynamic sizing.


As pointed out by @zett42 in their comment you can also address single bits with a bitfield struct (but for reasons of cache alignement this will probably use even more space):

struct S {
    // will usually occupy 4 bytes:
    unsigned b1 : 1, 
             b2 : 1,
             b3 : 1;
};

Upvotes: 8

Jerry Coffin
Jerry Coffin

Reputation: 490048

A bool uses at least one (and maybe more) byte of storage, so yes, at least 8 bits.

A vector<bool>, however, normally stores a bool in only one bit, with some cleverness in the form of proxy iterators and such to (mostly) imitate access to actual bool objects, even though that's not what they store. The original C++ standard required this. More recent ones have relaxed the requirements to allow a vector<bool> to actually be what you'd normally expect (i.e., just a bunch of bool objects). Despite the relaxed requirements, however, a fair number of implementations continue to store them in packed form in a vector<bool>.

Note, however, that the same is not true of other container types--for example, a list<bool> or deque<bool> cannot use a bit-packed representation.

Also note that due to the requirement for a proxy iterator (and such) a vector<bool> that uses a bit-packed representation for storage can't meet the requirements imposed on normal containers, so you need to be careful in what you expect from them.

Upvotes: 3

ephemient
ephemient

Reputation: 204678

The smallest unit of addressable memory is a char. A bool[N] or std::array<bool, N> will use as much space as a char[N] or std::array<char, N>.

It is permitted by the standard (although not required) that implementations of std::vector<bool> may be specialized to pack bits together.

Upvotes: -2

Related Questions