Search code examples
c++bit-fields

C++ - Defining 1 Bit Bools


What are the consequences of defining a structure as follows:

typedef struct {
    bool          Bit0 : 1;    //Bit 0
    bool          Bit1 : 1;
    bool          Bit2 : 1;
    bool          Bit3 : 1;
    bool          Bit4 : 1;
    bool          Bit5 : 1;
    bool          Bit6 : 1;
    bool          Bit7 : 1;     //Bit 7
    char          SomeOtherData;
}Char16Bits;

...

Char16Bits MyStructure;

MyStructure.Bit0 = true;
MyStructure.Bit1 = false;

In my test program everything seems fine, each of the "Bit0-7" only occupies 1 bit and I can see them in memory working as expected. The "SomeOtherData" char appears to be the second byte of the structure in memory when looking at the VS2010 Memory window which is all good.

However, can I reliably assume that each of these bits will always only occupy 1 bit? If I memcpy 2 bytes into this structure, will the 2nd byte always reliably occupy the "SomeOtherData" char element in my structure?


Solution

  • Structure packing is always compiler-dependent, but most compilers should put this in two bytes.

    You can rely on sizeof(MyStructure) being the total size of the data structure (taking into account padding as discussed here Why isn't sizeof for a struct equal to the sum of sizeof of each member?), and offsetof(Char16Bits,SomeOtherData) being the correct offset of SomeOtherData.

    If you need to write code that assumes particular sizes or offsets, use assert() or static_assert() so that the code isn't allowed to run on platforms that don't follow your assumptions.