What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?

后端 未结 3 696
一整个雨季
一整个雨季 2020-11-22 04:23

What does the following C++ code mean?

unsigned char a : 1; 
unsigned char b : 7;

I guess it creates two char a and b, and both of them sho

3条回答
  •  死守一世寂寞
    2020-11-22 05:09

    Strictly speaking, a bitfield must be a int, unsigned int, or _Bool. Although most compilers will take any integral type.

    Ref C11 6.7.2.1:

    A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type.

    Your compiler will probably allocate 1 byte of storage, but it is free to grab more.

    Ref C11 6.7.2.1:

    An implementation may allocate any addressable storage unit large enough to hold a bit- field.

    The savings comes when you have multiple bitfields that are declared one after another. In this case, the storage allocated will be packed if possible.

    Ref C11 6.7.2.1:

    If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined.

提交回复
热议问题