Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 896
DevNoteHQ Avatar asked May 21 '17 20:05

DevNoteHQ


1 Answers

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;
};
like image 129
πάντα ῥεῖ Avatar answered Sep 17 '22 01:09

πάντα ῥεῖ