Size of a structure having unsigned short ints

后端 未结 1 526
太阳男子
太阳男子 2021-01-29 15:29

I was surfing in one of our organisational data documents and I came across the following piece of code.

struct A {
 unsigned short int i:1;
 unsigned short int         


        
相关标签:
1条回答
  • 2021-01-29 16:20

    Yes, this is bitfield, indeed.

    Well, i'm not very much sure about c++, but In c99 standard, as per chapter 6.7.2.1 (10):

    An implementation may allocate any addressable storage unit large enough to hold a bit-field. 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 bits or overlaps adjacent units is implementation-defined. The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined. The alignment of the addressable storage unit is unspecified.

    That makes your structure size (1 bit + 1 bit + 14 bits) = 16 bits = 2 bytes.

    Note: No structure padding is considered here.


    Edit:

    As per C++14 standard, chapter §9.7,

    A member-declarator of the form

    identifieropt attribute-specifier-seqopt: constant-expression

    specifies a bit-field; its length is set off from the bit-field name by a colon. [...] Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined. Bit-fields are packed into some addressable allocation unit.

    0 讨论(0)
提交回复
热议问题