Search code examples
c++bit-fields

Do bitfields have any hidden costs or benefits aside from the obvious seeming benefit of saving space?


here is how you declare a bitfield:

unsigned m_bitfield1 : 2;  // a bitfield that occupies 2 bits
unsigned m_bitfield2 : 1;  // a bitfield that occupies 1 bit

a bit-field is simply a small field that has a specific size in bits.

my question is: can i use my own algorithms to treat default data types such as integer or float that occupy lots of unnecessary space as collection of smaller parts of arbitrary size, or use of bit-fields have some hidden benefits? thank you.


Solution

  • It is fine to use ints as a collection of bits that you access and manage yourself. However there are often un-thought-of costs to using the compiler generated bit fields (and possibly your own) that you should be aware of.